异步等待代码执行异常

时间:2020-02-12 23:11:39

标签: c# async-await task-parallel-library

我创建了一个简单的示例来了解C#中的异步/等待。

ReactDOM.render(
  <div style={{white-space: pre-line}}>{user_input}</div>,
  document.getElementById('preview')
);

因此,程序首先打印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); } } ,然后计算返回方法中的值。然后打印结果。

image

看起来不错。我的问题是,由于await不会阻塞评估异步方法的线程。我的理解是,如果异步花费很长时间,它将返回其调用方法。

对于我的示例,由于QuxAsync()需要很长时间,因此代码

This happens before await

未被阻止,将很快被评估。 我认为打印顺序应为

Console.WriteLine("Main");

但是不是,为什么?

1 个答案:

答案 0 :(得分:2)

我将排第二(第三?)其他人的建议,让您继续阅读和学习async。我偏爱我自己的async intro,但是最近有很多不错的人。

我的问题是,由于await不会阻塞评估异步方法的线程。我的理解是,如果异步花费很长时间,它将返回其调用方法。

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

我的async intro涵盖了两部分知识。

首先:await的工作方式是首先检查其参数。如果已经完成,则await继续执行-同步

第二:每个方法都被同步调用。包括async方法。唯一的异步时间是在async方法中有一个await的自变量 not 已经完成时;在这种情况下,该async方法将返回一个不完整的任务。

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