本文介绍了我为什么要preFER单曲“等待Task.WhenAll”在多个等待着?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在情况下,我不关心任务完成的顺序,只需要他们全部完成,我仍然应该使用等待Task.WhenAll
而不是多个等待
?例如,为 DoWord2
低于preferred方法 DoWork1
(为什么?):
使用系统;
使用System.Threading.Tasks;
命名空间ConsoleApp
{
类节目
{
静态异步任务<字符串> DoTaskAsync(字符串名称,诠释超时)
{
VAR开始= DateTime.Now;
Console.WriteLine(输入{0},{1},姓名,超时);
等待Task.Delay(超时);
Console.WriteLine(退出{0},{1},名称,(DateTime.Now - 启动).TotalMilliseconds);
返回名称;
}
静态异步任务DoWork1()
{
VAR T1 = DoTaskAsync(T1.1,3000);
VAR T2 = DoTaskAsync(T1.2,2000年);
VAR T3 = DoTaskAsync(T1.3,1000);
等待T1;等待T2;等待T3;
Console.WriteLine(DoWork1结果:{0}的string.join(,t1.Result,t2.Result,t3.Result));
}
静态异步任务DoWork2()
{
VAR T1 = DoTaskAsync(T2.1,3000);
VAR T2 = DoTaskAsync(T2.2,2000年);
VAR T3 = DoTaskAsync(T2.3,1000);
等待Task.WhenAll(T1,T2,T3);
Console.WriteLine(DoWork2结果:{0}的string.join(,t1.Result,t2.Result,t3.Result));
}
静态无效的主要(字串[] args)
{
。Task.WhenAll(DoWork1(),DoWork2())等待();
}
}
}
解决方案
是的,使用 WhenAll
,因为它传播的所有错误的一次。随着多个在等着你失去错误在先等待着一个动作。
我想这也使得读取code更容易,因为要直接记录在code中的语义。
In case I don't care about the order of task completion and just need them all to complete, should I still use await Task.WhenAll
instead of multiple await
? E.g, is DoWord2
below a preferred method to DoWork1
(and why?):
using System;
using System.Threading.Tasks;
namespace ConsoleApp
{
class Program
{
static async Task<string> DoTaskAsync(string name, int timeout)
{
var start = DateTime.Now;
Console.WriteLine("Enter {0}, {1}", name, timeout);
await Task.Delay(timeout);
Console.WriteLine("Exit {0}, {1}", name, (DateTime.Now - start).TotalMilliseconds);
return name;
}
static async Task DoWork1()
{
var t1 = DoTaskAsync("t1.1", 3000);
var t2 = DoTaskAsync("t1.2", 2000);
var t3 = DoTaskAsync("t1.3", 1000);
await t1; await t2; await t3;
Console.WriteLine("DoWork1 results: {0}", String.Join(", ", t1.Result, t2.Result, t3.Result));
}
static async Task DoWork2()
{
var t1 = DoTaskAsync("t2.1", 3000);
var t2 = DoTaskAsync("t2.2", 2000);
var t3 = DoTaskAsync("t2.3", 1000);
await Task.WhenAll(t1, t2, t3);
Console.WriteLine("DoWork2 results: {0}", String.Join(", ", t1.Result, t2.Result, t3.Result));
}
static void Main(string[] args)
{
Task.WhenAll(DoWork1(), DoWork2()).Wait();
}
}
}
解决方案
Yes, use WhenAll
because it propagates all errors at once. With the multiple awaits you lose errors if one of the earlier awaits throws.
I think it also makes reading the code easier because the semantics that you want are directly documented in code.
这篇关于我为什么要preFER单曲“等待Task.WhenAll”在多个等待着?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!