Friday, January 26, 2018

Blocking

Task.Delay()

If you are in an async method and you want to have it wait for a period of time before continuing your first thought might be to use Thread.Sleep(), but this would work the way you may think. Task.Delay() is what you want to use. Sleep just sleeps on the current thread which is the same as the thread that is calling the async method. Having an async method does NOT create threads unless the

Task.Run()

Task.Run() method is used to run a non-async method on another thread (from the thread pool by default). This is essentially just a background thread and has nothing to do with async. However since Task.Run() returns a Task you can await the result. This makes tracking the task and getting the result very easy.

Task.Run() is a good way to run a non-async method from an async method. There is overhead of spinning up an additional thread just to run this non-async code and then we would await the completion of the thread. This overhead is sometimes the only option if there is no async method available to call and all you have is a non-async method to call and you don't have access to change it.



1 comment:

Search Optimization said...

A great content and very much useful to the visitors. Looking for more updates in future.

Selenium Training in Chennai