LoginSignup
3

More than 5 years have passed since last update.

C# 便利関数 ExecuteSync 多重実行防止

Posted at

asp.netではリクエストはマルチスレッドでコールされますが、多重実行したくないときに、次の拡張関数に渡すことで多重実行を防げます。


        public static void ExecuteSync(Action SynchronousAction, Action OnBlocked)
        {
            string appKey = "MyState";

            var app = System.Web.HttpContext.Current.Application;
            app.Lock();
            var state = app[appKey];
            if (state == null)
            {
                app[appKey] = new object();
            }
            app.UnLock();

            if (state != null)
            {
                OnBlocked();
                return;
            }

            try
            {
                SynchronousAction();
            }
            finally
            {
                app.Lock();
                app.Remove(appKey);
                app.UnLock();
            }
            return;
        }

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3