开发者

Semaphores and Lock in ASP MVC3

开发者 https://www.devze.com 2023-04-01 00:15 出处:网络
I am working with Asp.net MVC 3. Any reason why I cannot create a single instance of a thread process in MVC? I am trying to allow a single instance of a worker process one at a time. however it is al

I am working with Asp.net MVC 3. Any reason why I cannot create a single instance of a thread process in MVC? I am trying to allow a single instance of a worker process one at a time. however it is allowing more than one instance at a time.

I followed the example at: http://msdn.microsoft.com/en-us/library/system.threading.semaphore.aspx

This is the code in my controller:

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

I also tried this example using 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 });
    }

-------------------------------- Worker ------------------------------------

    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.
     }


Your code has several problems, but the most important one is - you only lock the Thread.Start, but that doesnt promise you'll have only one concurrent thread, it only means that only the thread creation is locked.

If what you want to force the threads to work serially, you could use the following code:

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号