Question

Let's say I have this code :

  public class MyAsyncHandler : IHttpAsyncHandler
    {
      public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData)
      {
        MyAsynchOperation asynch = new MyAsynchOperation(cb, context, extraData);
        asynch.StartAsyncWork();
        return asynch;
      }
     //...

Now , if MyAsynchOperation is an IO operation , so it probably have internal methods (APM) of BeginFOO/EndFOO which are not tying a thread.

When the operation is finished , a new/same thread from the thread pool (via completion ports) is dealing with the response.

All ok.

But one of the things which makes me wonder is that IAsyncResult has this property :

System.Threading.WaitHandle AsyncWaitHandle { get; }

I'm familiar with WaitHadnle that it has a methods to block the current thread.
A thread waits, or blocks, at the turnstile by calling WaitOne (for example).

And so here is my questions :

Question #1

  • Assuming MyAsynchOperation is using the APM for IO , How(for what) does waitHAndle is being used if there is no blocking/tying a thread ?

Question #2

  • Assuming MyAsynchOperation is NOT using the APM and it's just my implementation which internally calls new Thread().start(do some calculation) which I later later call AsyncCallback's Callback ---- does waithandle here blocks a thread ?
Was it helpful?

Solution

#1:

The entire point of WaitOne here is to allow people to write synchronous code that waits for completion; if you don't need to use methods like WaitOne, WaitAny etc - then don't use them; that's fine.

#2:

In both cases, whether it uses a dedicated thread, or whether it completes via some other callback, yes it blocks a thread: it blocks the thread that has requested to be blocked by calling WaitOne. If you don't want that: don't call WaitOne.


Aside: since you specify 4.0, you might find it more intuitive to return a Task<T> instead, using TaskCompletionSource<T>. Edit: I realize now that this isn't an option due to satisfying the IHttpAsyncHandler.BeginProcessRequest method.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top