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:
What you wanna do here is to pass the result to the
xxxCompleted
method of your controller action withAsyncManagaer.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