Roman Ratskey Roman Ratskey - 29 days ago 9
C# Question

Async/Await vs Threads

In .Net 4.5 Microsoft has added the new

Async/Await
feature to simplify asynchronous coding. However, I wonder


  1. Can
    Async/Await
    completely replace the old way of using
    Threads
    ?

  2. Is
    Async/Await
    capable of doing whatever a
    Thread
    can do
    asynchronously?

  3. Can
    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?


Answer

came to 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.