Kelly Summerlin
Kelly Summerlin

Reputation: 661

How to make controller action truly async

I have the following controller:

public class PingController : ApiController 
{
    [Route("api/ping")]
    [HttpGet]
    public IHttpActionResult Ping()
    {
        var log = HostLogger.Get(typeof(PingController));
        log.Info("Ping called.");
        return Ok("Ping succeeded @ " + DateTime.UtcNow);
    }

    [Route("api/long-ping")]
    [HttpGet]
    public async Task<IHttpActionResult> LongPing(CancellationToken cancelToken)
    {
        await Task.Delay(30 * 1000);
        return Ok("Ping succeeded @ " + DateTime.UtcNow);
    }
}

If I execute LongPing, followed by Ping in different browser tabs, the Ping will execute and return before LongPing does -- which is exactly what I'm looking for. The problem is when I execute two LongPing calls the second one takes around 60s to complete (not 30 seconds). Chrome reports the second call has a latency of 58s (60s minus the time it took me to start the second request). It seems to me that both LongPing calls should execute in around 30s if I had this working correctly.

I also should mention that I'm hosting this in an OWIN hosting environment, not IIS. But I didn't think that made any difference but maybe someone will prove me wrong.

How do I make LongPing behave truly like an async request?

Upvotes: 2

Views: 422

Answers (2)

Kelly Summerlin
Kelly Summerlin

Reputation: 661

It turns out this is Chrome's behavior when calling the same URL. I always forget this when testing with Chrome. Normally I test with Fiddler, but this VM doesn't have Fiddler.

See this SO Q&A: Chrome treating smart url and causing concurrent requests pend for each other

Upvotes: 1

Haney
Haney

Reputation: 34762

It's quite likely that your session state is causing your problems. There's a long-winded explanation for this behaviour, but the short version is that a particular user session can only do one request at a time because the session state locks to ensure consistent state. If you want to speed this up, disable your cookies to test the session state hypothesis (you'll get 1 session state per request that way), or disable session state in the application. Your code is otherwise a-ok async wise.

Upvotes: 1

Related Questions