My takeaway from the "async and await keywords don't cause additional threads to be created" is that it simply uses threads already created from the thread pool
No, that's not true at all. async
and await
don't use the thread pool at all at a language level. It's entirely possible to write a program using async/await which only uses the initial "main" thread.
That doesn't mean that everything will happen on a single thread - it's just that async/await don't force extra threads to be created. The compiler itself doesn't generate any code to do that. It's entirely up to what you're awaiting. For example, you can task a task using Task.Run
, which will (usually) use the thread pool, and you can await that. Or you can await the result of calling Task.Delay
, which in itself doesn't start any threads but just schedules the task to be completed at a future time. Or you could use asynchronous IO, which may use IO completion ports but won't actually involve another thread running for most of the time that the task is "active".
A well-designed awaitable (if you're using anything built-in, this will include you) will schedule the continuation (all the code after await
) in the same context as you were in when you started awaiting it, unless you've specifically told it not to. That "context" may mean that you come back to the same thread (e.g. in a UI) but may not (e.g. in the thread pool context, it doesn't matter which thread pool thread the continuation runs on).
In my view, it's worth learning more about what async really does under the hood. There are lots of resource around this, both free and behind paywalls:
- The Visual Studio async home page
- An MSDN Magazine article by Stephen Cleary with lots of details
- "There is no thread" - another Stephen Cleary blog post addressing this specific issue
- Eric Lippert's async blog posts
- My async blog posts give a fair amount of detail, although they were mostly written during the CTP phase; the thrust of it is still correct, but some details have changed
- Chapter 15 of the third edition of my C# in Depth book is entirely about async/await
- Many Pluralsight courses on C# 5 will talk a lot about async; I have a course just about async which you may be interested in if you have a subscription