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

后端 未结 4 416
抹茶落季
抹茶落季 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 16:03

    You could use ManualResetEvents to block the main thread until any pending operations have completed.

    for example if you would like all timers to execute at least once then you could have an System.Threading.ManualResetEvent[] array with the initial state set to non-signalled

    So somewhere in your code you would have your timer setup and it's associated waithandle initialised.

    // in main setup method.. 
    int frequencyInMs = 600000; //10 mins 
    Timer timer = new Timer();
    timer.Elapsed += (s, e) => MyExecute();
    myTimers.Add(timer) 
    
    ManualResetEvent[] _waithandles = new ManualResetEvent[10];
    _waithandles[0] = new ManualResetEvent(false);
    
    // Other timers ... 
    timer = new Timer();
    timer.Elapsed += (s, e) => MyOtherExecute();
    myTimers.Add(timer)         
    _waithandles[1] = new ManualResetEvent(false);
    // etc, and so on for all timers 
    
    // then in each method that gets executed by the timer
    // simply set ManualReset event to signalled that will unblock it. 
    private void MyExecute() 
    {
        // do all my logic then when done signal the manual reset event 
        _waithandles[0].Set(); 
    }
    
    // In your main before exiting, this will cause the main thread to wait
    // until all ManualResetEvents are set to signalled  
    WaitHandle.WaitAll(_waithandles);    
    

    If you only wanted to wait for pending operations to finish then simply modify to something like this:

    _waithandles[0] = new ManualResetEvent(true); // initial state set to non blocking. 
    
    private void MyExecute() 
    {
        _waithandles[0].Reset(); // set this waithandle to block.. 
    
        // do all my logic then when done signal the manual reset event 
        _waithandles[0].Set(); 
    }
    

提交回复
热议问题