In .Net 4.5 Microsoft has added the new Async/Await
feature to simplify asynchronous coding. However, I wonder
Async/Await
completely replace the old way of using Threads
?Async/Await
capable of doing whatever a Thread
can do asynchronously?Async/Await
only be used with some methods like WebClient.DownloadStringAsync
or can I convert any synchronous method to make it use Async/Await
and not to block the main thread?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.
In this case threads outperform Async. Because Async like a single threaded program executes your tasks in order. But threads can execute both the tasks simultaneously.
As good as it sounds, parallelism is not ideal for I/O bound tasks; it works well with CPU bound job. So why asyncio is faster than multi-threading if they both belong to asynchronous programming? It's because asyncio is more robust with task scheduling and provides the user with full control of code execution.
It is a general misconception that both asynchronous programming and multithreading are the same although that's not true. Asynchronous programming is about the asynchronous sequence of Tasks, while multithreading is about multiple threads running in parallel.
can it completely replace the old way of using Threads ?
No. A thread can do many more useful things. Await is specifically designed to deal with something taking time, most typically an I/O request. Which traditionally was done with a callback when the I/O request was complete. Writing code that relies on these callbacks is quite difficult, await greatly simplifies it.
capable of doing what ever a Thread can do asynchronously ?
Roughly. Await just takes care of dealing with the delay, it doesn't otherwise do anything that a thread does. The await expression, what's at the right of the await keyword, is what gets the job done. Ideally it doesn't use a thread at all, it posts a driver request and once the driver completes the data transfer it generates a completion notification callback. Networking is by far the most common usage, latencies of hundreds of milliseconds are common and an inevitable side-effect of services moving from the desktop or a LAN into "the cloud". Using such services synchronously would make a UI quite unresponsive.
only can be used with some methods like WebClient.DownloadStringAsync
No. You can use it with any method that returns a Task. The XxxxAsync() methods are just precooked ones in the .NET framework for common operations that take time. Like downloading data from a web server.
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