I just started playing around with async/await in .Net 4.5. One thing I'm initially curious about, why is the async keyword necessary? The explanation I read was that it is a marker so the compiler knows a method awaits something. But it seems like the compiler should be able to figure this out without a keyword. So what else does it do?
There are several answers here, and all of them talk about what async methods do, but none of them answer the question, which is why
It's not "to direct the compiler to transform the function in a special way";
And this is why
it changes the method from a normal method to a object with callback which requires a totally different approach for code generation
and when something drastic like that happens it is customary to signify it clearly (we learned that lesson from C++)
The whole idea with keywords like "async" or "unsafe" is to remove ambiguity as to how the code they modify should be treated. In the case of the async keyword, it tells the compiler to treat the method modified as something that does not need to return immediately. This allows for the thread where this method is used to continue without having to wait on the results of that method. It's effectively a code optimization.
OK, here is my take on it.
There is something called coroutines that has been known for decades. ("Knuth and Hopper"-class "for decades") They are generalizations of subroutines, in such as not only do they get and release control at function start and return statement, but they also do it at specific points (suspension points). A subroutine is a coroutine with no suspension points.
They are PLAIN EASY to implement with C macros, as shown in the following paper about "protothreads". (http://dunkels.com/adam/dunkels06protothreads.pdf) Read it. I'll wait...
The bottom line of this is that the macros create a big
This is done without modifying the apparent flow of control of the code described in the "protothread".
Imagine now that you have a big loop calling all these "protothreads" in turn, and you get concurrently executing "protothreads" on a single thread.
This approach has two drawbacks:
There are workarounds for both:
And if you had compiler support to do the rewrite work that the macros and workaround do, well, you could just write your protothread code just as you intend and insert suspension points with a keyword.
And this is what
The coroutines in C# are reified as objects of (generic or non-generic) class
I find these keywords very misleading. My mental reading is:
Now. Do we really need to mark the function