我正在使用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 });
}
我也尝试使用lock这个例子: 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.
}
答案 0 :(得分:3)
你的代码有几个问题,但最重要的是 - 你只锁定了Thread.Start,但这并不能保证你只有一个并发线程,它只意味着只有线程创建被锁定。
如果要强制线程以串行方式工作,可以使用以下代码:
private static Object _lockKey = new Object();
public ActionResult SomeAction(int someParam)
{
ThreadPool.QueueUserWorkItem(doWork, SOME_STATE);
return SOMETHING;
}
private void doWork(object state)
{
lock (_lockKey)
{
/* Because of the static lockKey, this code will not be invoked serially */
}
}