Why is my async callback running on a single thread?

I am trying to use asynchronous calls to FtpWebRequest ( BeginGetResponse / EndGetResponse ).

However, it seems that the callback from BeginGetResponse works in the same thread as my application, when I was under the show, it would use a different (and pool thread) thread. This means that my applications block the callback before continuing.

I installed the proof of concept for LINQPad as follows:

 "Starting".Dump(); Thread.CurrentThread.GetHashCode().Dump(); Thread.CurrentThread.IsThreadPoolThread.Dump(); IAsyncResult result = request.BeginGetResponse((ar) => { "Inside Callback".Dump(); Thread.CurrentThread.GetHashCode().Dump(); Thread.CurrentThread.IsThreadPoolThread.Dump(); var resp = request.EndGetResponse(ar); "Callback Complete".Dump(); }, null); "After Callback".Dump(); 

This conclusion is output as follows:

 Starting 33 False Inside Callback 33 False Callback Complete After Callback 

I would expect something like this (assuming the callback took a lot of time to start):

 Starting 33 False Inside Callback 44 True After Callback // App continues despite callback running Callback Complete 

With a callback running in the same thread of the application, this means that something inside the callback takes a lot of time (for example, by entering Thread.Sleep for an argument for the sake of it), my application is blocked there. This means that I cannot configure the request timeout (for example, using ThreadPool.RegisterWaitForSingleObject ).

Did I miss something?

+4
source share
2 answers

When an asynchronous operation can be completed immediately by the BeginXXX method, it does not start the callback in the thread pool thread, but sets the IAsyncResult.CompletedSynchronously property to true and performs the callback synchronously.

+5
source

I assume the BeginGetResponse method calls the callback in the context of the call flow

0
source

All Articles