How Microsoft.Bcl.Async works?

梦想的初衷 提交于 2019-12-03 17:02:38

问题


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?


回答1:


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.




回答2:


MS2012 is installing .net 4.5 so you cannot get 'compile errors with 4.0' as you described



来源:https://stackoverflow.com/questions/22060691/how-microsoft-bcl-async-works

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!