在构造函数中调用4个异步方法paralel的问题 [英] Problem with calling 4 async method paralel in constructor
本文介绍了在构造函数中调用4个异步方法paralel的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在c#中的任务有问题,并且不知道如何使用async
await
.我有4种方法,例如:
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) {}
如何在构造函数中同时运行所有4种方法,以减少执行时间并优化cpu的使用.
How can I run all 4 methods simultaneously in the constructor, to reduce the execution time and optimize cpu usage.
我尝试了Parallel.Invoke(() =>
,但这不是最好的解决方案....
I tried Parallel.Invoke(() =>
but this not best solution....
推荐答案
您可以使用以下示例代码:
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.
更新:
这是完整答案:
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);
}
这篇关于在构造函数中调用4个异步方法paralel的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文