0

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
}
3
  • 1
    What exactly do you mean by "run together"? Commented Oct 1, 2018 at 4:45
  • Do you mean run asynchronously in parallel? Commented Oct 1, 2018 at 4:46
  • "run together" that means functions don`t wait for each other Commented Oct 1, 2018 at 5:08

4 Answers 4

4
public async Task BaseFun()
{
    await Task.WhenAll(Fun1(),
    Fun2(),
    Fun3());
   // do something after Fun1, Fun2 and Fun3 complete
}
Sign up to request clarification or add additional context in comments.

Comments

1

Just add await before the functions.

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

2 Comments

Need to be careful when using this kind of pattern in await functions, imagine each of these functions download data from website (each taking about 5 seconds). After first await the method will wait for it to complete before proceeding onto take 2. This would mean unnecessary hit on performance.
This would be the correct pattern when the Fun?() calls are not independent (ie, not threadsafe). The question is not totally clear.
0

also can do as

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

Comments

0

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?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.