简体   繁体   中英

How Microsoft.Bcl.Async works?

Microsoft.Bcl.Async enables developers to use async/await keywords without .NET Framework 4.5 that they are supposed to target to use them.

That's great, thanks to the incredibly hard work of people in the Microsoft CLR and language teams.

Now I am curious how this can work.

async/await require the compiler to do some heavy lifting to turn code into something that can do await operations.

The compiler originally throws compile errors under .NET Framework 4.0, even if it clearly knows what async/await mean(Visual Studio 2012/2013.)

So how does this library tell the compiler not to throw specific compile errors related to asynchronous operations, and do some code lifting just like being under .NET Framework 4.5?

async/await is nothing but C# 5.0 compiler transformation. There is no async/await at IL level.

One simple example would be the using() { } statement which is also a compiler transformation. It just converts the using statement to try/finally block. However, there is a dependency on existence of IDisposable interface which is defined in .NET 1.1.

Similarly, the async/await transformation depends on certain types like IAsyncStateMachine interface which are defined in .NET 4.5. The Microsoft.Bcl.Async gets those type definitions to .NET 4.0.

EDIT

How does the Microsoft.Bcl.Async assembly cause the compiler to recognize a new keyword (async/await)?

No it does not. C# 5.0 compiler already knows about the keywords and what to do with them. However, it can't find the required types as project is targeted to .NET 4.0. The Microsoft.Bcl.Async package brings in those types.

MS2012正在安装.net 4.5,因此您无法获得“编译错误4.0”,如您所述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM