How to run only 1 single long running task in separate thread in ASP.NET

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

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top