Thursday, August 12, 2010

Asp.Net - Handling Long Running Process in Web Development

Sometimes in web development we need to run long processes. During such time we come across browser request time out issues. Whether we use Ajax or not, if process is very long running, browser will through time out error. Also there are some processes which needs to be initiated in background, then user can redirect to other page. Once the Process is over user can retrieve the data from long running process.
In case of Ajax.Net if we use script manager then also we have to define time out for the request. Imagine the scenario in which we can’t predict what time the process will take to execute e.g. it may take 5-7 minutes in such cases browser may give timeout error.
In this article we will discuss about this issue and how to use Ajax to handle long running process; using IAsyncResult, ICallbackEventHandler.
Concept behind Logic
Web application is a client-server architecture, so when client hits server; server will reply. If long process is running on the server, then we need some mechanism by which we will come to know that long process is over. And using Ajax we can very well do polling. But when on server side, long running process is going on , rest of the code will not get execute unless that process overs. To handle this issue we will use IAsyncResult . Using this interface and delegates we will able to run asyncronous process on server side.
For this logic is we invoke one method on server side and continue with other tasks; once first method is over it will automatically call another server method so that we can update some parameters say VAR1 and VAR2. And using ICallback we will check for VAR1 and VAR2, as soon as we get updated values, we will change status of long running method on client. (In Demo code we have used Session Variable Named result )
About IAsyncResult, delegate and AsyncCallback in our code (Refer DEMO CODE for better understanding)
Classes which support asynchronous operation or method implements IAsyncResult interface. IAsyncResult objects are passed to methods invoked by AsyncCallback, when an asynchronous operation overs. Classes which supports AsyncCallback in their methods return object of IAsyncResult; check out FileStream.BeginRead and FileStream.EndRead, these methods support AsyncCallback hence return type is IAsyncResult. Same is true for BeginGetRequestStream method of WebRequest.
If we see the parameters in these method then there is one parameter “AsyncCallback callback”; now callback is the method which gets called once Async method is over. In our code this method is represented by CallBackMethod function.
In our this code, we have used async method of delegate, i.e. BeginInvoke and EndInvoke.
On server side, we have used delegate and on button click event function named DoSomething() get called. This function take cares of LongRunningMethod registration for delegate and invoking of LongRunningMethod; this will be asynchronouse invokation on server side. While invoking LongRunningMethod we register AsyncCallback method i.e. CallBackMethod. In CallBackMethod we get object of IAsyncResult class as paramter. In this method we have just called EndInvoke method of delegate.
CallBackMethod method can be used to do other operations which may be dependent on the LongRunningMethod.
We will write our LongRunningMethod,that will be as follows

Above methos is simple implemtation for longrunning method.
We will declare delegate for above function , parameters for delegate and method should be same.
private delegate void LongRun(string name);
Implementation of Async process on server side

On button click event we will call DoSomething function.

Long.BeginInvoke in DoSomething will invoke LongRunningMethod method.
While implenting this just check parameters for BeginInvoke in .net.
CallBackMethod get called automatically after LongRunningMethod. CallBackMethod is used to end the invokation of delegate.
Upto this point we were discussing about Asynchronouse method invocation on server side. Now we will talk about Ajax check using ICallbackEventHandler for LongRunningMethod. (Note: if your are new to ICallbackEvent Handler, check out my article on ICallback, you can also download ICallback Demo. )
On Button Click in Above code (i.e. in LongRunningProcess.aspx page in demo) we initiate Long Running Process and Redirect to RedirectedPage.aspx. On Redirected Page we use ICallback to check status of LongRunning Process. We have used Session["result"] to check the status. Please make sure that you are understanding the code.
Using ICallbackEventHandler client browser polls to server for chekcing whether LongRunningMethod is over or not; in predefined time interval. If the process is over we send SUCCESS to client side. So if response from server singnifise that the LongRunningMethod is over we update the client. (RedirectedPage.aspx takes care of the status check, on this page we can have our other elements and other business logic, while in backend we can check for status of longrunning process.)
Here I assume that you are aware about the ICallbackEvent Handler, if not then please go through my article related to ICallback.
Download Demo Code For Free --> , ICallbackEvent Handler
Submit this story to DotNetKicks


Robert December 23, 2010 at 1:16 AM  

Do you have an example of how to do this using MVC 2.0 ?

amar October 11, 2011 at 9:35 PM  

this is causing session expiry when hosted on IIS. Any idea how to resolve it ?

Ashish November 4, 2011 at 12:59 PM  

@ Amar, Yes we can avoide session expiry, use ICallback to check if the process is over or not, and set session expiry to sliding. Every time you get a call back from client side to check whether Process is over, access the desired session variable.
Make sure your IIS is not getting rest due to Lake of Memory. Shared and Chip Hosting has this problem