Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perform Multiple Async Method Calls Sequentially

Tags:

c#

async-await

It seems like I have come across the answer to this question in the past but now I cannot locate it.

Suppose I have two asynchronous methods, Method1 and Method2. If I need to call Method1 and then Method2 sequentially (read, Method1 must complete before Method2), is the following code correct?

await Method1();
await Method2();

Based on information from the accepted answer to another SO question here and information in the MSDN article here, I believe this is the correct way to do it. Also, this code appears to work but I don't want to introduce a subtle bug that will be much harder to track down later.

like image 228
Jason Richmeier Avatar asked Nov 18 '14 14:11

Jason Richmeier


2 Answers

I know this thread is a bit old, but I'd like to add an issue I ran into using async methods.

This is purely for insight, and something I figured out by trial-and-error.

If you create a void() method, you cannot await it unless you call the method like this:

await Task.Run(() => Method());

...with the method declaration:

void Method() {...}

Calling the function using await Task.Run executes multiple methods without waiting for any previous functions to execute.

If for example you have:

void Method1() {...}
void Method2() {...}
void Method3() {...}

And you call them like this:

await Task.Run(() => Method1());
await Task.Run(() => Method2());
await Task.Run(() => Method3());

The await operation won't wait for Method1 to finish before calling Method2 etc.

To overcome this, create the function like this:

async Task Method1() {...}
async Task Method2() {...}
async Task Method3() {...}

And call them like this:

await Method1();
await Method2();
await Method3();
like image 159
GrammatonCleric Avatar answered Nov 15 '22 23:11

GrammatonCleric


Yes, this is the correct way. They will execute sequentially.

The important quote from the msdn:

The await operator tells the compiler that the async method can't continue past that point until the awaited asynchronous process is complete.

If you wanted to execute them in parallel, you'd have to use something like this:

var t1 = DoTaskAsync(...);
var t2 = DoTaskAsync(...);
var t3 = DoTaskAsync(...);

await Task.WhenAll(t1, t2, t3);
like image 40
DasKrümelmonster Avatar answered Nov 15 '22 23:11

DasKrümelmonster