C# – ASP.net MVC – AsyncController and Session

asp.net-mvcasynchronousc

I was playing around with asynchronous controllers in ASP.net MVC just to see how they work. In one of my asynchronous action methods I wanted to simulate a long running method by looping a few times and doing a Thread.Sleep:

for(int x = 1; x <= 10; x++) {
    Thread.Sleep(1000);

    Session["progress"] = x * 10;
}

I wanted a quick and dirty way of reporting the progress of the long running operation so I just used session state. I wouldn't use it in a normal application but I noticed that in another non-asynchronous action method this session state was not being persisted:

public ActionResult ReportProgress() {
    int progress = 0;

    if( Session["progress"] != null ) {
        progress = (int)Session["progress"];
    }

    return Json(progress);
}

In the ReportProgress method, this session variable is always null. When I debug the other async method, Session is being persisted.

Does anyone have any insight into why the asynchronous method and the synchronous method don't appear to have the same session?

Best Answer

This links should give you an idea:

Using an Asynchronous Controller in ASP.NET MVC (Working with the BeginMethod/EndMethod Pattern)

Quote:

If an asynchronous action method calls a service that exposes methods by using the BeginMethod/EndMethod pattern, the callback method (that is, the method that is passed as the asynchronous callback parameter to the Begin method) might execute on a thread that is not under the control of ASP.NET. In that case, HttpContext.Current will be null, and the application might experience race conditions when it accesses members of the AsyncManager class such as Parameters. To make sure that you have access to the HttpContext.Current instance and to avoid the race condition, you can restore HttpContext.Current by calling Sync() from the callback method.

What you wanna do here is to pass the result to the xxxCompleted method of your controller action with AsyncManagaer.Paramater dictionary and set the session there.

You are safe inside xxxCompleted method. See the link that I have given. It will walk you through the process.

But keep in mind that this approach is not the way going forward. Async operations on ASP.NET MVC will dramatically changed on the next version with the availability of await keyword.

More info:

Task Support for Asynchronous Controllers