I have a aspx page in which i create reports and charts on the fly. Creation of these charts and reports takes a lot of time because of which a blank screen is shown to the user until the creation completes.
To solve this problem I am trying to trigger report generation in a separate thread on page load and when the reportgeneration completes i am trying to set a session variable to indicate completion. I have a AJAX timer which keeps checking for this flag.
protected void Page_Load( object sender, EventArgs e )
{
if ( !IsPostBack )
{
ThreadPool.QueueUserWorkItem( new WaitCallback( DoLongRunningProcess ) );
}
}
public void GenerateReport( object state )
{
///generate report
Session[ "done" ] = true;
}
The problem is that Session is null(Session state can only be used when enableSessionState is set to true, either in a configuration file or in the Page directive. Please also make sure that System.Web.SessionStateModule or a custom session state module is included in the <configuration>\<system.web>\<httpModules> section in the application configuration.) when i am trying set the completion flag.
Can you guys tell me how to workaround this problem.
The problem is that in a new thread, HttpContext.Current (and Session in it) is not available.
One solution is to create an instance that you pout in Session and also sens to worker thread as a parameter:
Declare a Status class:
public class MyStatus {
public Exception Exception { get; set; }
public bool IsDone { get; set; }
}
Before start processing, put an instance in the Session that your ajax callback can check. Also gives object as argument to worker thread.
protected void Page_Load( object sender, EventArgs e )
{
if ( !IsPostBack )
{
MyStatus myStatus = new MyStatus();
Session[“MyStatus”] = myStatus;
ThreadPool.QueueUserWorkItem(DoLongRunningProcess , myStatus );
}
}
In your worker thread, set the flag that processing is done.
public void GenerateReport( object state )
{
MyStatus myStatus = state as MyState;
}
In your ajax callback, check status. If you are done, also remove status from Session.
MyStatus myStatus = Session[“MyStatus”] as MyState;
if (myStatus.IsDone)
{
// do something.
}