How to implement a mutex on the server side of an MVC 4 web application

I am not an MVC expert, but I am sure it is possible; however, I do not know how to do this in MVC 4.

For testing, I use the default web application specified when creating the site using VS 2012.

For simplicity, let us consider that HomeController.Index () gets exactly at the same time by several users (for example, 3). I want to execute a method that is mutexed, since only one will execute at a time; hence forcing them in series. I don't care what order. I know the warnings about page locking and that everything should be asynchronous, 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(); } 
+6
source share
1 answer

If you want to limit execution to one at a time, you will 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 perhaps 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(); } 
+6
source

All Articles