Wait for System.Threading.Timer Callbacks to Complete before Exiting Program

后端 未结 4 412
抹茶落季
抹茶落季 2021-01-11 15:12

I have a List. Each Timer fires at a configurable interval (default 10 minutes). All call the same callback method (with a diffe

4条回答
  •  清酒与你
    2021-01-11 15:53

    The accepted answer from Tomek is nice, but incomplete. If the Dispose function returns false, it means that there is no need to wait for completion, as the thread is already finished. If you make an attempt to wait on a WaitHandle in such a case, WaitAll will never return, so you created yourself a function that arbitrarily freezes your application/thread.

    Here is how it should look:

        void WaitUntilCompleted(List myTimers)
        {
            List waitHnd = new List();
            foreach (var timer in myTimers)
            {
                WaitHandle h = new AutoResetEvent(false);
                if (timer.Dispose(h))
                {
                    waitHnd.Add(h);
                }
            }
            WaitHandle.WaitAll(waitHnd.ToArray());
        }
    

提交回复
热议问题