A
Anonieko
How do you run a long running task in ASP.NET in thread and
avoid multiple instances of this task from running?
I saw a solution somewhere but do you have a better one?
[WebMethod]
publicvoid StartTask1()
{
string processKey = this.Context.Request.UserHostAddress + "1";
// Create a lock object to prevent 1 user from running task 1 //
multiple times. string threadLockKey = "thread1" +
this.Context.Request.UserHostAddress;
object threadLock = this.Context.Cache[threadLockKey];
if (threadLock == null)
{
threadLock = newobject();
this.Context.Cache[threadLockKey] = threadLock;
}
// Only allow 1 running task per user. if (!
Monitor.TryEnter(threadLock, 0))
return;
// Simulate a time-consuming task. for (int i = 1; i <= 100; i++)
{
// Update the progress for this task.
this.Context.Cache[processKey] = i;
Thread.Sleep(100);
}
// The task is done. Release the lock. Monitor.Exit(threadLock);
}
avoid multiple instances of this task from running?
I saw a solution somewhere but do you have a better one?
[WebMethod]
publicvoid StartTask1()
{
string processKey = this.Context.Request.UserHostAddress + "1";
// Create a lock object to prevent 1 user from running task 1 //
multiple times. string threadLockKey = "thread1" +
this.Context.Request.UserHostAddress;
object threadLock = this.Context.Cache[threadLockKey];
if (threadLock == null)
{
threadLock = newobject();
this.Context.Cache[threadLockKey] = threadLock;
}
// Only allow 1 running task per user. if (!
Monitor.TryEnter(threadLock, 0))
return;
// Simulate a time-consuming task. for (int i = 1; i <= 100; i++)
{
// Update the progress for this task.
this.Context.Cache[processKey] = i;
Thread.Sleep(100);
}
// The task is done. Release the lock. Monitor.Exit(threadLock);
}