异步等待代码未按预期执行

async await code executing not as expected

我创建了一个简单的例子来理解 async/await 在 C# 中。

class Program
{
    static void Main(string[] args)
    {
        var t = BarAsync();
        Console.WriteLine("Main");
    }

    private static async Task BarAsync()
    {
        Console.WriteLine("This happens before await");
        int i = await QuxAsync();
        Console.WriteLine("This happens after await. This result of await is " + i);
    }

    private static Task<int> QuxAsync()
    {
        int c = 0;
        for (int i = 0; i < int.MaxValue; i++)
        {
            c++;
        }
        Console.WriteLine("in the middle processing...");
        return Task.FromResult(c);
    }
}

所以程序首先打印 This happens before await 然后计算 return 方法的值。然后打印结果。

看起来不错。我的问题是,因为 await 不会阻塞评估异步方法的线程。我的理解是,如果异步需要很长时间,它将 return 到它的调用方法。

对于我的例子,因为QuxAsync()需要很长时间,所以代码

Console.WriteLine("Main");

没有被屏蔽,很快就会进行评估。 我认为打印顺序应该是

 This happens before await
 Main
 in the middle processing...
 This happens after await. This result of await is 2147483647

然而却不是,为什么?

我将第二(第三?)其他人建议您继续阅读和了解 async。我偏爱自己的 async intro,但现在有很多不错的。

My question is that since await doesn't block the thread that evaluates the async method. My understanding is if the async takes a long time it will return to its calling method.

这是错误的部分。异步与花费多长时间完全无关。

我的 async intro.

中缺少两个知识点。

首先:await首先检查它的参数。如果已经完成,则 await 继续执行 - 同步.

其次:每个方法都是同步调用的。包括 async 方法。异步发生的唯一时间是当 async 方法有一个 await 时,其参数是 not 已经完成;在这种情况下,async 方法 returns 是一项未完成的任务。

将这两者放在一起应该可以解释为什么您的代码实际上是同步运行的。