Why does System.Timer.Timer still fire events when Enabled is set to false?

前端 未结 5 548
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-12 04:35

I have attempted to create a derived class of Timer that allows for a \'Pause\' latch to be set to keep the worker thread from reactivating the timer. However, Elapsed event

5条回答
  •  囚心锁ツ
    2021-01-12 05:23

    Another option is to suppress the event??? I can't explain what is going but the theory presented below should allow you to circumvent this little problem you have discussed. As Steve mentioned put a 'Watch and break point on the enabled property' that you are try set and make sure it is actually being set.

    How would I tackle this:

    Catch and check for the 'Enabled' property and remove '-=' the subscribing method (handler) as of when needed and then re-add '+=' it again when you do need handle the 'Elapsed' event.

    I have used this style quite a few times on a few different WinForms project. If you don't want the 'Elapsed' event to be handled programmatically create a check for and remove it when a certain condition is met and then add it when the opposite condition is met.

    if (paused) // determine pause logic to be true in here
    {
       timer.Elapsed -= ... // remove the handling method.
    }
    else
    {
       timer.Elapsed += ... // re-add it in again
    }
    

    The above code logic will allow you code to ignore the 'Elapsed' event ever time it is raised whilst the 'Paused' flag is true. I hope the above helps

提交回复
热议问题