13 Jan 2011 @ 11:31 AM 

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);
        }
    }
Posted By: boyd21
Last Edit: 14 Apr 2011 @ 09:48 PM

EmailPermalink
Tags
Tags: , , ,
Categories: .Net, Programming


 

Responses to this post » (None)

 
Tags
Comment Meta:
RSS Feed for comments

 Last 50 Posts
Change Theme...
  • Users » 3
  • Posts/Pages » 30
  • Comments » 0
Change Theme...
  • VoidVoid « Default
  • LifeLife
  • EarthEarth
  • WindWind
  • WaterWater
  • FireFire
  • LightLight

GeekPub



    No Child Pages.