简体   繁体   中英

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
}
public async Task BaseFun()
{
    await Task.WhenAll(Fun1(),
    Fun2(),
    Fun3());
   // do something after Fun1, Fun2 and Fun3 complete
}

Just add await before the functions.

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

also can do as

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

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM