I have just tested something that I was sure would fail miserably, but to my surprise, it worked flawlessly, and proves to myself that I am still quite mystified by how async-await
works.
I created a thread, passing an async void
delegate as the thread's body.
Here's an oversimplification of my code:
var thread = new Thread( async () => {
while( true ) {
await SomeLengthyTask();
...
}
});
thread.Start();
thread.Join();
The thing is that as far as I understand, when the execution hits the await
keyword, there is an implicit return from the method, in this case the body of the looping thread, while the rest of the code is wrapped in a callback continuation.
Because of this fact, I was pretty sure that the thread would terminate as soon as the await
yielded execution, but that's not the case!
Does anybody know how this magic is actually implemented? Is the async
functionality stripped down and the async
waits synchronously or is there some black magic being done by the CLR that enables it to resume a thread that has yielded because of an await
?