【发布时间】:2011-08-29 10:58:59
【问题描述】:
我正在使用 Asp.net MVC 3。为什么我不能在 MVC 中创建线程进程的单个实例?我试图一次允许一个工作进程的单个实例。但是它一次允许多个实例。
我按照以下示例进行操作: http://msdn.microsoft.com/en-us/library/system.threading.semaphore.aspx
这是我控制器中的代码:
private static Semaphore _pool;
public ActionResult StartBots(int id)
{
_pool = new Semaphore(0, 1);
Thread t = new Thread(SingletonWorker);
t.Start();
_pool.Release(1);
return RedirectToAction("index", new { id = id });
}
我还尝试了使用锁的这个例子: http://msdn.microsoft.com/en-us/library/c5kehkcz(v=VS.80).aspx
private Object thisLock = new Object();
public ActionResult StartBots(int id)
{
Thread t = new Thread(SingletonWorker);
lock (thisLock)
{
t.Start();
}
return RedirectToAction("index", new { id = id });
}
-------------------------------- 工人 -------------- ----------------------
private static void SingletonWorker()
{
_pool.WaitOne(); <== this only applies to the Semaphore example.
// Do something here.
Thread.Sleep(rand.Next(4) * 200 + 1000);
// Do something else here.
}
【问题讨论】:
标签: asp.net-mvc-3 locking semaphore