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