Morteza
Morteza

Reputation: 191

How to wait for async functions in c#

I have 3 async function that must run together, like this

public async Task Fun1()
{
  // do something
}
public async Task Fun2()
{
  // do something
}
public async Task Fun2()
{
  // do something
}

in my base function I call this functions this functions must run together how to wait for this functions until all complete?

public async Task BaseFun()
{
    Fun1()
    Fun2()
    Fun3()
   // do something after Fun1, Fun2 and Fun3 complete
}

Upvotes: 0

Views: 176

Answers (4)

Alexander
Alexander

Reputation: 614

You can also use Task.WaitAll.

var taskArray = new Task[3]
{
    Fun1(),
    Fun2(),
    Fun3()
};
Task.WaitAll(taskArray);

BTW, why are your Fun1-3 methods also public when you call them through a public base method?

Upvotes: 0

Akash Kava
Akash Kava

Reputation: 39916

public async Task BaseFun()
{
    await Task.WhenAll(Fun1(),
    Fun2(),
    Fun3());
   // do something after Fun1, Fun2 and Fun3 complete
}

Upvotes: 4

Steve Tolba
Steve Tolba

Reputation: 1487

Just add await before the functions.

public async Task BaseFun()
{
    await Fun1();
    await Fun2();
    await Fun3();
   // do something after Fun1, Fun2 and Fun3 complete
}

Upvotes: 1

Arphile
Arphile

Reputation: 861

also can do as

public async Task BaseFun()
{
    await Fun1();
    await Fun2();
    await Fun3();
    // do something after Fun1, Fun2 and Fun3 complete
}

Upvotes: 0

Related Questions