Pergunta

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?

Foi útil?

Solução

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.

Outras dicas

In the case you have outlined there is no practical difference as you immeadiately wait for the asynchronous method to complete before moving on to the next.

However, if you restructured your code something like this you might realize the power of asynchronous programming:

public async void Main() {
    Task performTask = AsyncTask1();
    //This method can continue without having to wait for AsyncTask1 to complete
    DoSomething();
    //Here we await the AsyncTask1 because perhaps other code further 
    //down is depending on it
    await performTask;
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top