如何实现MVC 4 Web App服务器端互斥锁

时间:2022-04-30 14:30:59

I'm no MVC expert, but I'm fairly sure this is implementable; however, I don't know how to do it in MVC 4.

我不是MVC专家,但我相信这是可行的;但是,我不知道如何在MVC 4中做到这一点。

For testing, I'm using the default web app given when you create a site using VS 2012.

对于测试,我使用的是使用VS 2012创建网站时提供的默认Web应用程序。

Consider, for simplicity, that HomeController.Index() is hit at exactly the same time by multiple users (for example 3). I want to execute a method that is mutexed so as only one will execute at a time; hence forcing them serially. I don't care what order. I know of the warnings about blocking a page and that everything should be async, but for this I need to block for a very short period of time.

为简单起见,考虑HomeController.Index()被多个用户完全同时命中(例如3)。我想执行一个互斥的方法,因为一次只执行一个;因此迫使他们连续。我不在乎什么顺序。我知道有关阻止页面的警告,并且所有内容都应该是异步的,但为此我需要阻止很短的时间。

public class HomeController : Controller {
    private String dosomething() {
        String str;
        str = "SomeValue"; //<-- Will vary
        return str;
    }

    public ActionResult Index() {
        String str;
        // How do I do implement the following, preferably with a timeout to be safe
        Lock(dosomething);
            str = dosomething();
        unLock(dosomething);
        return View();
    }

1 个解决方案

#1


6  

If you want to restrict the execution to one at a time, then you'll need a static lock object:

如果要一次将执行限制为一个,那么您将需要一个静态锁定对象:

public class HomeController : Controller {
    private static object _lockobject = new object();

And then:

public ActionResult Index() {
    String str;
    lock (_lockobject)
    {
        str = dosomething();
    }
    return View();
}

If you need a timeout, then maybe use Monitor.TryEnter instead of lock:

如果您需要超时,那么可以使用Monitor.TryEnter而不是lock:

public ActionResult Index() {
    String str;
    if (Monitor.TryEnter(_lockobject, TimeSpan.FromSeconds(5)))
    {
        str = dosomething();
        Monitor.Exit(_lockobject);
    }
    else str = "Took too long!";
    return View();
}

#1


6  

If you want to restrict the execution to one at a time, then you'll need a static lock object:

如果要一次将执行限制为一个,那么您将需要一个静态锁定对象:

public class HomeController : Controller {
    private static object _lockobject = new object();

And then:

public ActionResult Index() {
    String str;
    lock (_lockobject)
    {
        str = dosomething();
    }
    return View();
}

If you need a timeout, then maybe use Monitor.TryEnter instead of lock:

如果您需要超时,那么可以使用Monitor.TryEnter而不是lock:

public ActionResult Index() {
    String str;
    if (Monitor.TryEnter(_lockobject, TimeSpan.FromSeconds(5)))
    {
        str = dosomething();
        Monitor.Exit(_lockobject);
    }
    else str = "Took too long!";
    return View();
}