how to lock an asp.net mvc action?

后端 未结 6 668
情话喂你
情话喂你 2020-12-01 05:46

I\'ve written a controller and action that I use as a service. This service runs quite a costly action. I\'d like to limit the access to this action if there is already a cu

6条回答
  •  情歌与酒
    2020-12-01 06:16

    Having read and agreed with the above answer I wanted a slightly different solution: If you want to detect a second call to an action, use Monitor.TryEnter:

    if (!Monitor.TryEnter(Lock, new TimeSpan(0)))
    {
        throw new ServiceBusyException("Locked!");
    }
    try
    {
    ...
    }
    finally {
        Monitor.Exit(Lock);
    }
    

    Use the same static Lock object as detailed by @danludwig

提交回复
热议问题