我测试C#异步的asynchronousity /等待和跨越一个惊喜,其中用于ContinueWith随后的代码不等待前面的任务完成就来了:C#链式ContinueWith不是在等待前一个任务来完成
public async Task<int> SampleAsyncMethodAsync(int number,string id)
{
Console.WriteLine($"Started work for {id}.{number}");
ConcurrentBag<int> abc = new ConcurrentBag<int>();
await Task.Run(() => { for (int count = 0; count < 30; count++) { Console.WriteLine($"[{id}] Run: {number}"); abc.Add(count); } });
Console.WriteLine($"Completed work for {id}.{number}");
return abc.Sum();
}
[Test]
public void TestAsyncWaitForPreviousTask()
{
for (int count = 0; count < 3; count++)
{
int scopeCount = count;
var c = SampleAsyncMethodAsync(0, scopeCount.ToString())
.ContinueWith((prevTask) =>
{
return SampleAsyncMethodAsync(1, scopeCount.ToString());
})
.ContinueWith((prevTask2) =>
{
return SampleAsyncMethodAsync(2, scopeCount.ToString());
});
}
}
输出显示运行执行0.0,1.0和2.0正确异步执行,但随后的X.1和十,得到几乎立即开始和十,实际完成:这是与下面的测试方法执行
在x.1之前。例如。如下记录:
[2] Run: 0
[2] Run: 0
[2] Run: 0
Completed work for 2.0
Started work for 0.1
Started work for 0.2 <-- surprise!
[0] Run: 2
[0] Run: 2
[0] Run: 2
[0] Run: 2
[0] Run: 2
看来continueWith仅将在第一个任务(0)等,无论后续的链条。 我可以通过在第一个Continuewith块中嵌套第二个ContinueWith来解决问题。
我的代码有问题吗?我假设Console.WriteLine尊重FIFO。
['ContinueWithWith'是一种极其低级的管道方法](http://blog.stephencleary.com/2013/10/continuewith-is-dangerous-too.html)。你应该使用'await'而不是'ContinueWith'。 –