问题
I have a problem with tasks in c#, and don't know how to use async
await
. I have 4 methods, something like:
private async Task Name(parameters) {}
How can I run all 4 methods simultaneously in the constructor, to reduce the execution time and optimize cpu usage.
I tried Parallel.Invoke(() =>
but this not best solution....
回答1:
You can use this sample code:
Task[] tasks = new Task[4];
tasks[0] = Method0();
tasks[1] = Method1();
tasks[2] = Method2();
tasks[3] = Method3();
await Task.WhenAll(tasks);// If you have to wait all the tasks to be finished.
//await Task.WhenAny(tasks); //If any of them finished.
Update:
Here is the full answer:
static async Task<List<int>> MethodTest(int i)
{
await Task.Delay(10);
return new List<int>() { i, i, i };
}
async Task method()
{
Task<List<int>>[] tasks = new Task<List<int>>[4];
tasks[0] = MethodTest(0);
tasks[1] = MethodTest(1);
tasks[2] = MethodTest(2);
tasks[3] = MethodTest(3);
await Task.WhenAll(tasks);
Console.WriteLine(tasks[0].Result);
}
来源:https://stackoverflow.com/questions/60893319/problem-with-calling-4-async-method-paralel-in-constructor