How to block a timer while processing the elapsed event?

后端 未结 5 1685
臣服心动
臣服心动 2021-02-13 09:00

I have a timer that needs to not process its elapsed event handler at the same time. But processing one Elapsed event may interfere with others. I implemented the bel

5条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-13 09:31

    If LookForItWhichMightTakeALongTime() is going to take a long time, I would suggest not using a System.Windows.Forms.Timer because doing so will lock up your UI thread and the user may kill your application thinking that it has frozen.

    What you could use is a BackgroundWorker (along with a Timer if so desired).

    public class MyForm : Form
    {
      private BackgroundWorker backgroundWorker = new BackgroundWorker();
    
      public MyForm()
      {
        InitializeComponents();
        backgroundWorker.DoWork += backgroundWorker_DoWork;
        backgroundWorker.RunWorkerCompleted +=
                                    backgroundWorker_RunWorkerCompleted;
        backgroundWorker.RunWorkerAsync();
      }
    
      private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
      {
        e.Result = LookForItWhichMightTakeALongTime();
      }
    
      private void backgroundWorker_RunWorkerCompleted(object sender,
                                                 RunWorkerCompletedEventArgs e)
      {
        found = e.Result as MyClass;
      }
    }
    

    And you can call RunWorkerAsync() from anywhere you want to, even from a Timer if you want. And just make sure to check if the BackgroundWorker is running already since calling RunWorkerAsync() when it's running will throw an exception.

    private void timer_Tick(object sender, EventArgs e)
    {
      if (!backgroundWorker.IsBusy)
        backgroundWorker.RunWorkerAsync();
    }
    

提交回复
热议问题