我正在努力解开C#异步编程,下面的模式显然是错误的,但是我不明白.我打算做的就是解雇n个任务,然后等待它们全部完成.当我明白我感到困惑时,我开始将事情提炼下来,并最终创造了这个:
private async Task<bool> doLoop()
{
int loopCnt = 3;
int[] sleeperReturns = new int[loopCnt + 1];
for (int i = 0; i < loopCnt; i++)
{
System.Diagnostics.Debug.WriteLine("doLoop: i={0} calling Sleeper", i);
Task.Run(async () => { sleeperReturns[i] = await sleep(i); });
System.Diagnostics.Debug.WriteLine("doLoop: i={0} called Sleeper", i);
}
return true;
}
private async Task<int> sleep(int i)
{
System.Diagnostics.Debug.WriteLine("Sleep: begins i={0}", i);
await Task.Delay(5000 + i * 1000);
System.Diagnostics.Debug.WriteLine("Sleep: ends i={0}", i);
return i;
}
Run Code Online (Sandbox Code Playgroud)
这会产生以下输出:
doLoop: i=0 calling Sleeper
doLoop: i=0 …Run Code Online (Sandbox Code Playgroud)