If a method is running on a thread tool thread and it awaits another method, will it return to the thread pool during the await so that it can possibly execute another task?
Asked
Active
Viewed 503 times
0
-
Yes, that's sort of the point. – Raymond Chen Nov 14 '19 at 00:28
-
I was curious about this because when I call ```StreamReader.readAsync()``` , the same thread pool thread seems to be the one that returns to execute the code that appears after the await. It was waiting for a telnet response. What is the likely hood that the same thread always comes back to finish the job? – RomanOwensby Nov 14 '19 at 00:33
-
It depends on what that other method is doing. But yes, assuming the current thread is a thread pool thread, and it's awaiting an operation that is genuinely asynchronous (which could involve also running in a thread pool thread, but may instead just involve an asynchronous I/O operation, so no other thread involved), **and** (very important) the current thread is "async all the way up" (i.e. each call is to an async method and is awaited), then the current thread will yield to the caller all the way back up to the top of the thread pool thread, causing it to be returned to the pool. – Peter Duniho Nov 14 '19 at 00:34
-
1_"the same thread pool thread seems to be the one that returns to execute the code that appears after the await"_ -- that all depends on the method that was called. Not all async methods complete asynchronously. I/O is notorious for being able to complete synchronously, due to buffered data. And of course, even if completed asynchronously, there's always a chance that the same thread will be reused from the pool. – Peter Duniho Nov 14 '19 at 00:35
-
If your app has only one task busy at a time, then the odds of the same thread pool thread being chosen is close to 100%, because that single thread can service all of the tasks. Just like if you had a bunch of threads, but only one of them was doing something at a time, then a single processor can service all the threads. – Raymond Chen Nov 14 '19 at 01:08
1 Answers
0
If a method is running on a thread pool thread and it awaits another method, will it return to the thread pool during the await so that it can possibly execute another task?
Yes. That's the essential purpose of await The thread exits the method, returning a Task to the calling code. Then the thread goes on with whatever it was doing, typically either running a message loop on a UI, or being returned to the thread pool.

David Browne - Microsoft
- 80,331
- 6
- 39
- 67