我对异步的理解是否正确?

时间:2016-11-26 02:27:38

标签: c# .net multithreading asynchronous async-await

我已经阅读了至少十几篇文章,我想我终于明白了。批评我的以下解释。

如果我在一个函数中使用async关键字,它会向函数调用者发出信号,当它到达函数内的await关键字时/ strong>然后它可以在函数调用之后继续执行任何独立工作,直到返回await ed函数的结果,然后它可以从它停止的地方返回结束

2 个答案:

答案 0 :(得分:2)

{I}关键字在等待方面不会影响被叫方中的任何内容。无论来自哪里,等待任何 async都是合法的。让我们来看看这个例子:

Task

如您所见 - async Task Main() { Console.WriteLine("Starting A now."); GetResult(); Console.WriteLine("Finished A now."); Console.WriteLine("Starting B now."); await GetResult(); Console.WriteLine("Finished B now."); Console.WriteLine("Starting C now."); GetResultAync(); Console.WriteLine("Finished C now."); Console.WriteLine("Starting D now."); await GetResultAync(); Console.WriteLine("Finished D now."); } Task GetResult() { return Task.Delay(5000).ContinueWith(a => Console.WriteLine("Finished!")); } async Task GetResultAync() { await Task.Delay(5000).ContinueWith(a => Console.WriteLine("Finished!")); } 能够等待结果,无论该方法是否为Main。 Async只是简单地指示编译器:

  1. 该方法将调用async,并需要转换为状态机,
  2. 撰写async时(return aa),将结果打包成int

答案 1 :(得分:2)

“async”修饰符用于声明/签名方法,以指示(到编译器)该方法可能使用“await”调用一个或多个异步操作。 “async”允许在方法中使用“await”。 “async”修饰符不是在方法中使用,它用于方法签名,如“public”和“private”关键字。

类似:(example taken from here:

public async Task<int> AccessTheWebAsync() { ... }

您可以按如下方式调用上述方法:

Task<int> accessWebTask = AccessTheWebAsync();
... --> code that does not depend on the result of the previous line
var result = await accessWebTask;
... --> code that should not execute until the operation above is done

or shorter form:   
10 var result = await AccessTheWebAsync();
11    ... code after awaited operation

“await”操作符表示暂停点,也就是说等待操作之后的代码 要求等待操作(第10行)在其余代码之前完成(第11行)等等)可以执行。 “await”可用于void返回方法,在这种情况下,没有等待,这是一个火灾和忘记操作。

编译器代表您生成代码,以便所有这些都能正常工作。

“async / await”的另一个好处是代码可读性(线性流,异步代码读取像同步)和异常处理,大部分时间都是如此。

This article shows the many ways asynchronous operations can be accomplished (with and without "async/await")

还要记住,“async / await”与多线程几乎没什么关系。它旨在帮助非阻塞操作(数据库/文件系统/网络)和UI响应。 This SO post is a good read. / This series is worth reading also.

And so is this MS article (Synchronous and Asynchronous I/O).

如果您对更具概念性的观点感兴趣,请查看以下文章: The difference between asynchronous and non-blockingwhich links to this nice SO post

And this one is a FAQ on async/await.