C# 链式 ContinueWith 不等待上一个任务完成

Tro*_*itz 3 c# asynchronous continuewith

我正在测试 C# async/await 的异步性,遇到了一个惊喜,即 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();
        }
Run Code Online (Sandbox Code Playgroud)

这是使用以下测试方法执行的:

        [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());
                });
            }
        }
Run Code Online (Sandbox Code Playgroud)

输出显示运行 0.0、1.0 和 2.0 的执行正确异步执行,但随后的 x.1 和 x.2 几乎立即开始,并且 x.2 实际上在 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
Run Code Online (Sandbox Code Playgroud)

似乎 continueWith 只会等待第一个任务(0)而不管后续的链。我可以通过在第一个 Continuewith 块中嵌套第二个 ContinueWith 来解决问题。

我的代码有问题吗?我假设 Console.WriteLine 尊重 FIFO。

Yel*_*yev 5

简而言之,您希望ContinueWith等待先前返回的对象。TaskContinueWith操作中返回一个对象(甚至 a )对返回的值没有任何作用,它不会等待它完成,它会返回它并传递给延续(如果存在)。

确实会发生以下事情:

  • 你跑 SampleAsyncMethodAsync(0, scopeCount.ToString())
  • 完成后,执行continuation 1:

    return SampleAsyncMethodAsync(1, scopeCount.ToString());
    
    Run Code Online (Sandbox Code Playgroud)

    当它偶然发现 时await Task.Run,它会返回一个任务。即,它不会等待 SampleAsyncMethodAsync 完成。

  • 然后,continuation 1 被认为已经完成,因为它已经返回了一个值(任务)
  • 继续运行 2。

如果您手动等待每个异步方法,那么它将因此运行:

for (int count = 0; count < 3; count++)
{
    int scopeCount = count;

    var c = SampleAsyncMethodAsync(0, scopeCount.ToString())
    .ContinueWith((prevTask) =>
    {
        SampleAsyncMethodAsync(1, scopeCount.ToString()).Wait();
    })
    .ContinueWith((prevTask2) =>
    {
        SampleAsyncMethodAsync(2, scopeCount.ToString()).Wait();
    });
}    
Run Code Online (Sandbox Code Playgroud)

使用ContinueWith(async t => await SampleAsyncMethodAsync...也不起作用,因为它会导致包装Task<Task>结果(在这里解释得很好)。

此外,您可以执行以下操作:

for (int count = 0; count < 3; count++)
{
    int scopeCount = count;

    var c = SampleAsyncMethodAsync(0, scopeCount.ToString())
        .ContinueWith((prevTask) =>
        {
            SampleAsyncMethodAsync(1, scopeCount.ToString())
                .ContinueWith((prevTask2) =>
                {
                    SampleAsyncMethodAsync(2, scopeCount.ToString());
                });
        });   
}
Run Code Online (Sandbox Code Playgroud)

然而,它创建了某种回调地狱并且看起来很混乱。

您可以使用await使此代码更简洁:

for (int count = 0; count < 3; count++)
{
    int scopeCount = count;

    var d = Task.Run(async () => {
        await SampleAsyncMethodAsync(0, scopeCount.ToString());
        await SampleAsyncMethodAsync(1, scopeCount.ToString());
        await SampleAsyncMethodAsync(2, scopeCount.ToString());
    });
}   
Run Code Online (Sandbox Code Playgroud)

现在,它为 3 个计数运行 3 个任务,因此每个任务将运行number等于 1、2 和 3 的异步方法。