简体   繁体   中英

Tasks in parallel using C#. Am I doing this right?

I've already search and read about, I just want to make sure if I am right. I have three methods that I want to run in parallel, and I want to make sure that all of them are done before continue. They are all async, and this code are inside an async method. I've done this:

public async ProcessBegin() {
   //... some code

   await SomeProcess();
   await AnotherMethod().
}

public async SomeProcess() {
   //.. some code    

   var tasks = new Task[3];
   tasks[0] = method1();
   tasks[1] = method2();
   tasks[2] = method3();

   Task.WaitAll(tasks);
}

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

Is this right?

Task.WaitAll blocks synchronously so you might use Parallel.Invoke if this is intended:

Parallel.Invoke(() => method1(), () => method2(), () => method3());

This works as long as the methodX methods themselves are not asynchronous. Parallel.ForEach doesn't work with async actions.

If you want to wait for the tasks to complete asynchronously, you should use Task.WhenAll :

var tasks = new Task[3];
tasks[0] = method1();
tasks[1] = method2();
tasks[2] = method3();

await Task.WhenAll(tasks);
public async Task SomeProcess()
{
    //.. some code    

    await Task.WhenAll(method1(), method2(), method3());
}

Use Task.WhenAll which returns a new Task that completes once all the provided tasks have also completed.

You don't need to create the array manually because Task.WhenAll accepts params Task[] .

Using Task.WaitAll , as you have tried, will block the current thread until the tasks complete, hence rendering the method synchronous.

Furthermore, it could cause deadlocks depending on the synchronisation context of your app, as method1 / method2 / method3 may attempt to resume on the thread blocked by WaitAll .

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