Question

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.

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

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.

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();
    }
Was it helpful?

Solution

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:

public ActionResult Index() {
    String str;
    if (Monitor.TryEnter(_lockobject, TimeSpan.FromSeconds(5)))
    {
        str = dosomething();
        Monitor.Exit(_lockobject);
    }
    else str = "Took too long!";
    return View();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top