A solution here could be to use a shared variable which unless set to false
will allow the thread to continue, like tickRunning
to control the loop in the below code example:
using System;
using System.Threading;
namespace SharedFlagVariable
{
class Program
{
static volatile bool tickRunning; // flag variable
static void Main(string[] args)
{
tickRunning = true;
Thread tickThread = new Thread(() =>
{
while (tickRunning)
{
Console.WriteLine("Tick");
Thread.Sleep(1000);
}
});
tickThread.Start();
Console.WriteLine("Press a key to stop the clock");
Console.ReadKey();
tickRunning = false;
Console.WriteLine("Press a key to exit");
Console.ReadKey();
}
}
}
P.S. If you prefer to use System.Threading.Task
library then check out this post explaining how to Cancel Task
using CancellationToken approach.