views:

23

answers:

2

Hi All,

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.

+1  A: 

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:

  1. Declare a Status class:

    public class MyStatus { public Exception Exception { get; set; } public bool IsDone { get; set; } }

  2. 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 ); } }

  3. In your worker thread, set the flag that processing is done.

    public void GenerateReport( object state ) { MyStatus myStatus = state as MyState;

    ///generate report
    myStatus.IsDone = true;
    

    }

  4. 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.

    // cleanup.
    Session.Remove("MyStatus");
    

    }

Andreas Paulsson
That works. Thank You
Vinay B R
A: 

try to add to web.config in section that tag:

<add name="Session" type="System.Web.SessionState.SessionStateModule" />

in some cases you need to add a remove tag

<remove name="Session" />
<add name="Session" type="System.Web.SessionState.SessionStateModule" />
x2