gkelly
gkelly

Reputation: 288

HttpTaskAsyncHandler - seems to block but I know something is wrong

In the code below there is a HttpTaskAsyncHandler that calls doit that first delays 5 seconds and writes a string out to browser.

If I have two browser tabs open and call this page on both. The first responds in 5 seconds and the second in 10.

Why does the second request wait for first to complete? The delay was just to represent time taken to do work.

public class MyHandler : HttpTaskAsyncHandler
{
    public override bool IsReusable
    {
        get
        {
            return true;
        }
    }

    public override Task ProcessRequestAsync(HttpContext p_ctx)
    {
        return doit(p_ctx);
    }

    static int _count = 0;
    async Task doit(HttpContext p_ctx)
    {
        await Task.Delay(5000);
        p_ctx.Response.Write("doit " + (++_count).ToString());
    }

}

Upvotes: 1

Views: 284

Answers (1)

Kenneth
Kenneth

Reputation: 28747

Async does not mean concurrent. When you define an Async handler, it essentially means that you return the thread to the thread-pool when it's awaiting the call.

What's happening in your case, is that IIS Express queues up the requests. It does this because it needs an exclusive lock on the session:

Extract from http://msdn.microsoft.com/en-us/library/ms178581.aspx

Concurrent Requests and Session State

Access to ASP.NET session state is exclusive per session, which means that if two different users make concurrent requests, access to each separate session is granted concurrently. However, if two concurrent requests are made for the same session (by using the same SessionID value), the first request gets exclusive access to the session information. The second request executes only after the first request is finished. (The second session can also get access if the exclusive lock on the information is freed because the first request exceeds the lock time-out.) If the EnableSessionState value in the @ Page directive is set to ReadOnly, a request for the read-only session information does not result in an exclusive lock on the session data. However, read-only requests for session data might still have to wait for a lock set by a read-write request for session data to clear.

Possible options:

  • Execute the second request in a different browser (or Incognito mode)
  • Disable SessionState

Upvotes: 0

Related Questions