I have a system that spawns a LOT of sub-processes that must run in parallel
- The main thread for a request will spawn sub-processes and wait for them to complete.
- Those sub-processes do some processing
- then talk to a remote API
- then do more processing of the results from the API
- then the main thread continues when all sub-processes are complete (or timeout hit)
We have trouble with thread counts, so we want to reduce the number of threads active by trying to release the threads whilst we wait for the remote API.
Originally we used WebRequest.GetResponse()
for the API call which naturally is holding an idle thread whilst waiting for the API.
The we started using an EAP model (Event-based Async Programming ... all the various .NET methods that use IAsyncResult) , where we call BeginGetResponse(CallbackTrigger)
, with WaitHandle
s passed back to the main thread which then triggered the post-API processing.
As we understand it, this means that the sub-process thread terminates, and the Callback is triggered by a network-card-level interupt which triggers a new thread to initiate the callback. i.e. there's no thread sitting waiting to run CallbackTrigger
whilst we wait for the API call.
If people could confirm this understanding that would be good?
We are now considering moving to a TPL model (Task Parallel Library ... Task<T>
), using WebRequest.GetResponseAsync()
which is await
able. I'm under the impression that this is part of what await
\ async
does... that await
passes control back up the call stack whilst the remote source waits, and that if I initiate a bunch of await
able Tasks
and then call Tasks
.WaitAll
then that won't be holding onto a thread for each Task whilst that task is awaiting on the remote API.
Have I correctly understood this?