Roman Ratskey Roman Ratskey - 1 year ago 90
C# Question

Async/Await vs Threads

In .Net 4.5 Microsoft has added the new

feature to simplify asynchronous coding. However, I wonder

  1. Can
    completely replace the old way of using

  2. Is
    capable of doing whatever a
    can do

  3. Can
    only be used with some methods like
    or can I convert any synchronous method to make it use
    and not to block the main thread?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download