Friday, October 12, 2007

ASP.NET - Performing long running process asynchronously with out duplication

Sometimes in our web pages we need to perform some long running process. You must be agree that instead of watching wait cursor for long running process, user can do some other activity in same web application with out blocking. Those who do not know AJAX or want to do some quick fix in their ASP.NET code, following is the code which targets following objectives:
  1. User should not be blocked on web page, he can perform some other activity. That means after post back, process should be run in background and user instantly gets control after starting the process.
  2. Web server connection time out for long running process.
  3. Even instantly getting control after starting the process, user should be able to start the same process only after completion of previous process started by the same user. I used mutex for it.
Following is the code:
using System.Threading;

// Button click event
protected void btnLoad_Click(object sender, EventArgs e)
{
try
{
ThreadPool.QueueUserWorkItem(new WaitCallback(LoadLog));
}
catch (Exception ex)
{
lblMessage.Text = "Your job could not be submittited due to following error:
" + ex.Message;
lblMessage.CssClass = "Error";
}
lblMessage.Visible = true;
}

// In above code LoadLog is the function which starts long running process
// Following is the code for LoadLog
private void LoadLog(object state)
{

string mutexKey =Thread.CurrentPrincipal.Identity.Name;
mutexKey = mutexKey.Replace(@"\", "_"); // Required otherwise mutex will consider its a file system path
Mutex mMutex = new Mutex(false, mutexKey + "_LoadLogs");
mMutex.WaitOne();
try
{
//Here your long running process
Thread.Sleep(1000000); // Don't try this line, just for example.
}
finally
{
mMutex.ReleaseMutex();
}
}

No comments: