2011-08-29 212 views
0

我正在使用Asp.net MVC 3.任何我無法在MVC中創建線程過程的單個實例的原因?我試圖一次只允許一個工作進程的單個實例。但是它一次允許多個實例。ASP中的信號量和鎖定MVC3

我跟着這個例子: 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. 
    } 

回答

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 */ 
    } 
} 
+0

你會怎麼寫呢? – Mario

+0

我已經用示例更新了我的答案 – sternr

+0

好吧,我把工作進程中的鎖移動了,它工作正常。謝謝! – Mario