Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why not use a sync method instead of await Async task?

Async method:

public void Main(){
    await Asynctask1;
    DoSomething();
}

public async Task AsyncTask1(){
    //Async logic here
}

Sync method:

public void Main(){
    SyncMethod1();
    DoSomething();
}

I think I'm missing something here. Assuming that SyncMethod1() and Asynctask1() both do the same thing, aren't these 2 constructs in the end the same result, namely that DoSomething() doesn't start until the method before finishes?

like image 951
Nzall Avatar asked May 09 '14 07:05

Nzall


1 Answers

namely that DoSomething() doesn't start until the method before finishes?

There's a difference between asynchrony and sequential. When you always await your asynchronous methods immediately, you end up with asynchronous sequential code, which at first glance does appear to behave similarly to synchronous sequential code. (On a side note, this similarity is the entire point of the async/await keywords). However, there's one important difference.

Let's say the operation is some I/O thing, like getting an HTTP resource. SyncMethod1 will do the HTTP get synchronously; that is, it sends out the HTTP request and then blocks the thread until it gets the HTTP response. AsyncTask1 will do the HTTP get asynchronously; that is, it sends out the HTTP request and then returns an incomplete Task. Later, when the HTTP request comes in, the AsyncTask1 method will resume and complete the returned Task, and the code after the await is run (i.e., DoSomething).

The asynchronous way is more complicated but has one key advantage: it does not block a thread. So, UI threads are freed to enable a responsive UI and ASP.NET threads are freed to handle other requests.

I have an async intro on my blog that may help as you learn.

like image 100
Stephen Cleary Avatar answered Oct 08 '22 19:10

Stephen Cleary