Exit a method if another thread is executing it

后端 未结 4 2138
既然无缘
既然无缘 2021-02-07 13:18

I have a method in a multi-threaded application and I\'d like the following behavior when this method is invoked:

  1. If no other threads are currently executing the m
4条回答
  •  醉梦人生
    2021-02-07 14:10

    Here's a helper method for this purpose:

    static class Throttle
    {
        public static void RunExclusive(ref int isRunning, Action action)
        {
            if (isRunning > 0) return;
    
            bool locked = false;
            try
            {
                try { }
                finally
                {
                    locked = Interlocked.CompareExchange(ref isRunning, 1, 0) == 0;
                }
    
                if (locked) action();
            }
            finally 
            { 
                if (locked) 
                    Interlocked.Exchange(ref isRunning, 0); 
            }
        }
    }
    

    and use it like:

    private int _isTuning = 0;
    private void Tune() { ... }
    
    ...
    
    Throttle.RunExclusive(ref _isTuning, Tune);
    

提交回复
热议问题