Apply this attribute to a method to force that method to be synchronous. Be careful as this does not sync it the call on a per request basis. So if you have thousands of requests for this method at the same time, they’ll all be waiting.
public class LockAttribute : ActionFilterAttribute
{
private static readonly object _firstLock = new object();
private static readonly object _lockObj = new object();
private static bool isLocked = false;
private bool hasLock = false;
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
lock (_firstLock)
{
if (isLocked)
{
System.Threading.Monitor.Enter(_lockObj);
isLocked = hasLock = true;
}
else
{
isLocked = hasLock = System.Threading.Monitor.TryEnter(_lockObj);
}
}
base.OnActionExecuting(filterContext);
}
public override void OnResultExecuted(ResultExecutedContext filterContext)
{
if(hasLock)
System.Threading.Monitor.Exit(_lockObj);
base.OnResultExecuted(filterContext);
}
}

Categories
Tag Cloud
Blog RSS
Comments RSS
Last 50 Posts
Back
Void « Default
Life
Earth
Wind
Water
Fire
Light 