- 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.
- Web server connection time out for long running process.
- 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.
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();
}
}