Pausing and interrupting threads
In this section, we will look at pausing and interrupting threads. An example of why you would need to pause or interrupt a thread is if the code running is a debugger. If a thread is executing and it hits a breakpoint, it would need to be paused.
The most common way to pause/delay a thread is to call Thread.Sleep(millisecondsDuration)
, but this may freeze the main thread and your users may think your program has stopped working, leading them to terminate it.
A better way to delay a thread is to let Task.Delay(TimeSpan)
run in the background. This will allow the thread to work in the background and prevent the delayed thread from stopping the main thread from doing its work.
The following code shows how to delay a thread:
static void Main(string[] args)
{
Console.WriteLine($"Current Time: {DateTime.Now}");
var delay = Task.Delay(TimeSpan.FromSeconds(5));
...