依次执行多个异步方法调用 [英] Perform Multiple Async Method Calls Sequentially
问题描述
似乎我过去曾遇到过这个问题的答案,但现在找不到了.
It seems like I have come across the answer to this question in the past but now I cannot locate it.
假设我有两个异步方法,Method1和Method2.如果我需要先调用Method1然后依次调用Method2(读取,Method1必须在Method2之前完成),那么下面的代码正确吗?
Suppose I have two asynchronous methods, Method1 and Method2. If I need to call Method1 and then Method2 sequentially (read, Method1 must complete before Method2), is the following code correct?
await Method1();
await Method2();
根据来自另一个SO问题的已接受答案的信息此处,并且MSDN文章此处中的信息,我相信这是正确的方法做吧.另外,此代码似乎可以正常工作,但我不想引入一个细微的错误,以后很难找到.
Based on information from the accepted answer to another SO question here and information in the MSDN article here, I believe this is the correct way to do it. Also, this code appears to work but I don't want to introduce a subtle bug that will be much harder to track down later.
推荐答案
是的,这是正确的方法.它们将按顺序执行.
Yes, this is the correct way. They will execute sequentially.
msdn中的重要报价:
The important quote from the msdn:
await运算符告诉编译器,异步方法不能继续到该点为止,直到等待的异步过程完成为止.
The await operator tells the compiler that the async method can't continue past that point until the awaited asynchronous process is complete.
如果您想并行执行它们,则必须使用如下代码:
If you wanted to execute them in parallel, you'd have to use something like this:
var t1 = DoTaskAsync(...);
var t2 = DoTaskAsync(...);
var t3 = DoTaskAsync(...);
await Task.WhenAll(t1, t2, t3);
这篇关于依次执行多个异步方法调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!