我不是 MVC 专家,但我相当确定这是可以实现的;但是,我不知道如何在 MVC 4 中做到这一点。
为了进行测试,我使用了使用 VS 2012 创建网站时提供的默认 Web 应用程序。
为简单起见,请考虑多个用户(例如 3)在同一时间点击 HomeController.Index()。我想执行一种互斥的方法,以便一次只有一个执行;因此迫使他们连续。我不在乎什么顺序。我知道有关阻止页面的警告,并且一切都应该是异步的,但为此我需要阻止很短的时间。
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();
}
如果你想限制一次执行一个,那么你需要一个静态锁对象:
public class HomeController : Controller {
private static object _lockobject = new object();
进而:
public ActionResult Index() {
String str;
lock (_lockobject)
{
str = dosomething();
}
return View();
}
如果您需要超时,那么也许可以使用Monitor.TryEnter http://msdn.microsoft.com/en-us/library/system.threading.monitor.tryenter%28v=vs.110%29.aspx代替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();
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)