Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 263
Dean Seo Avatar asked Feb 27 '14 06:02

Dean Seo


1 Answers

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.

like image 85
YK1 Avatar answered Oct 22 '22 11:10

YK1