Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
294 views
in Technique[技术] by (71.8m points)

c# - 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.

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();

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Yes, this is the correct way. They will execute sequentially.

The important quote from the msdn:

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...