I have a TPL Task that does two things. First, it calls a web service. Second, it inserts some data into a database. I have up to 20 Tasks started at one time doing this sam
Would the thread pool have more threads at its disposal if I made the service call and database call with async and await() instead of making them blocking calls?
It depends on what you mean by "making use of async-await".
When you use Task.Run
, behind the scenes, the Task
class uses the ThreadPool
to offload work using a ThreadPool
thread.
If your service doesn't expose a true async api and you uses Task.Run
to queue your work, you will still be blocking a threadpool thread to do IO bound work, regardless of the use of async-await
. In your question you state that both calls are blocking calls, and in that case the answer is no, the threadpool thread used to make those blocking calls woul still be blocked.
If your service and database calls were true async APIs (one that doesn't consume any extra threads to do its work), you could advantage of async-await
, as when you await
on one of those calls (and you shouldn't need to use Task.Run with them at all), the current thread will yield control back to the caller, and can be used in the meanwhile to do more work. If this is the case, then yes.
My theory (and I'm not sure why I think this) is that the thread is busy doing nothing while waiting on the blocking web service and can't return its resources temporarily to the pool. But I wonder if the Tasks were waiting for async calls to finish whether the main Task thread would be able to switch to let other stuff process while waiting.
Your theory is correct. If the main job of the queued threadpool work is to make an IO bound request then its spending of most its time simply blocking until the request finishes.
When you await
a Task
, control yields back to caller. Lets assume your service call was a REST call, you could use HttpClient
which exposes true non-thread consuming async methods such as GetAsync
, PostAsync
, and when you await
these calls, your calling thread is released to do more work in the meanwhile.