Problem with calling 4 async method paralel in constructor [closed]

霸气de小男生 提交于 2020-05-09 17:29:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!