开发者

Async calls with new keyword 'await'

开发者 https://www.devze.com 2023-01-31 17:05 出处:网络
I\'ve used async methods today, calling methods asynchronously and using the caller\'s callback methods.

I've used async methods today, calling methods asynchronously and using the caller's callback methods.

Recently, I can across this post which talks about the new way to do this using the new await keyword. Other than saving few lines of code, w开发者_如何学运维hat are the main advantages of this new model?

Does it offer a built in solution for when you make two different async calls but want the control to return to only one of the caller's callback, after both have completed?

What does CTP (Community Technical Preview) mean? Is this new keyword available in next version of C# and VB.NET?


From Eric Lippert's Blog post Asynchrony in C# 5, Part One

The designers of C# 5.0 realized that writing asynchronous code is painful, in so many ways. Asynchronous code is hard to reason about, and as we've seen, the transformation into a continuation is complex and leads to code replete with mechanisms that obscure the meaning of the code.

As the article explains like iterator blocks, anonymous methods, query comprehensions and dynamic types the intent is to make something that is hard, easy.

As for Community Technical Preview bit. Typically it means that "await" will be in the next version of C#, but there's no guarantee that something about it won't change. So if you write something (code or blog posts) and its breaks don't blame them.


I would say that "saving a few lines of code" is an understatement. The await keyword lets the compiler generate the all the necessary wiring to allow you to write an asynchronous method that looks pretty much like a regular synchronous method.

The current paradigm of using callbacks has a number of limitations, such as in inability to use certain language constructs, complex error handling and so forth. All this complexity is effectively hidden by the compiler generated code.

The Async CTP ships with a couple of Word documents, that go in to far more detail. If you haven't looked at them already, I recommend you do so. The "Asynchrony in .NET.docx" document has a very elaborate example, that shows the extend of the compiler generated code.


If you want to start a new task upon async operation completed you don't need the "await" keyword. All you need is Task.ContinueWhenAll method.

Regarding CTP - it means this is in "alpha" stage and may contain bugs and is not finalized (may change in the future. For example - "await" keyword will change to something else, or will have different syntax rules).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号