Make multiple calls to the async method in sequence

It seems that I have come across an answer to this question in the past, but now I cannot find it.

Suppose I have two asynchronous methods, Method1 and Method2. If I need to call Method1 and then Method2 sequentially (read, Method1 should 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 works, but I don't want to introduce a subtle bug that will be much harder to track down later.

+3


source to share


2 answers


Yes, that's the right way. They will be executed sequentially.

Important quote from msdn:

The pending operator informs the compiler that the async method cannot continue at this point until the pending asynchronous process completes.



If you want to execute them in parallel, you will need to use something like this:

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

await Task.WhenAll(t1, t2, t3);

      

+11


source


I know this thread is a bit outdated, but I would like to add the problem I am facing using async methods.

This is purely for understanding, and something I figured out through trial and error.

If you create a method void()

, you cannot await

, unless you call that method like this:

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

      

... with a method declaration:

void Method() {...}

      

Calling a function using await Task.Run

performs multiple methods without waiting for any previous functions to complete.

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 pending operation will not wait for Method1 to complete until Method2 is called, etc.

To overcome this, create a function like this:

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

      

And call them like this:

await Method1();
await Method2();
await Method3();

      

+1


source







All Articles