Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using async and await with System.Threading.Thread.Sleep

I started using .NET4.5 for async and await. All examples seem to use the following to simulate a long term operation:

await Task.Delay(3000);

Now my long term calculations are really similar to:

System.Threading.Thread.Sleep(3000)

for example:

for(i=0;i<1000000000;i++)
    i=i*2;

How do I make this work with async and await? Now it seems I can 'only' use methods like webrequests, WCF, etc... with this great new method.

Where am I missing the point?

like image 885
Enrico Avatar asked Oct 14 '12 07:10

Enrico


People also ask

Is thread sleep asynchronous?

The amazing thing is that the Thread. sleep will not block anymore! It's fully async. And on top of that, virtual threads are super cheap.

Does await block the thread?

The await operator doesn't block the thread that evaluates the async method. When the await operator suspends the enclosing async method, the control returns to the caller of the method.

Does async await use thread pool?

The async and await keywords don't cause additional threads to be created. Async methods don't require multithreading because an async method doesn't run on its own thread. The method runs on the current synchronization context and uses time on the thread only when the method is active.

What is the difference between Task delay and thread sleep?

delays did not cause thread jumps. And all of this research is to propose: while thread. sleep will block a thread and task. delay will not and has a cancellation token, unless your app is pretty complex, it really doesn't matter as on the surface: task.


1 Answers

await Task.Run(() => Thread.Sleep(10000))

Would work, but it's rather pointless

like image 195
erikkallen Avatar answered Sep 28 '22 01:09

erikkallen