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?
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.
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.
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.
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.
await Task.Run(() => Thread.Sleep(10000))
Would work, but it's rather pointless
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With