Saturday, December 5, 2020

Thread.Sleep vs. Task.Delay in c#

Thread.Sleep vs. Task.Delay in c# 

The biggest difference between Task.Delay and Thread.Sleep is that Task.Delay is intended to run asynchronously. It does not make sense to use Task.Delay in synchronous code. It is a VERY bad idea to use Thread.Sleep in asynchronous code.


void ThreadSleepSample()

{

            Thread.Sleep(1000);

 }


 async Task TaskDelaySample()

{

         await Task.Delay(1000);

 }

Both Thread.Sleep() and Task.Delay() are used to suspend the execution of a program (thread) for a given timespan. 


Thread.Sleep()

This is the classic way of suspending execution. This method will suspend the current thread until the given amount of time has elapsed. When you call Thread.Sleep in the above way, there is nothing you can do to abort this except waiting until the time elapses or by restarting the application. That’s because Thread.Sleep suspends the thread that's making the call. 


Task.Delay()

Task.Delay acts in a very different way than Thread.Sleep. Basically, Task.Delay will create a task which will complete after a time delay. Task.Delay is not blocking the calling thread so the UI will remain responsive.

Behind the scenes there is a timer ticking until the specified time. Since the timer controls the delay, we can cancel the delay at any time simply by stopping the timer. To cancel,we can modifying the above TaskDelaySample method as follows:

CancellationTokenSource tokenSource = new CancellationTokenSource(); 

async Task TaskDelaySample()
   try
   {
       await Task.Delay(1000, tokenSource.Token);
   }
   catch (TaskCanceledException ex)
   {
       
   }
   catch (Exception ex)
   { 
   
   }
}

In the call to Task.Delay we 've added a cancellation token.  When the task gets cancelled, it will throw a TaskCanceledException Jump .We are catching the exception and suppressing it, because we don't want to show any message about that.

No comments:

Post a Comment

Open default email app in .NET MAUI

Sample Code:  if (Email.Default.IsComposeSupported) {     string subject = "Hello!";     string body = "Excellent!";    ...