How do I gracefully stop a System.Threading.Timer?

后端 未结 4 784
星月不相逢
星月不相逢 2021-02-13 03:57

I have a Windows Service implemented in C# that needs to do some work every so often. I\'ve implemented this using a System.Threading.Timer with a callback method t

4条回答
  •  终归单人心
    2021-02-13 04:39

    As described in "Concurrent Programming on Windows":
    Create a dummy class InvalidWaitHandle, inheriting from WaitHandle:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.ComponentModel;
    using System.Data;
    using System.Diagnostics;
    using System.Threading;
    
    namespace MyNameSpace
    {
        class InvalidWaitHandle : WaitHandle
        {
    
        }
    }
    

    Hence you can Dispose a System.Threading.Timer properly like this:

    public static void DisposeTimer()
    {
       MyTimer.Dispose(new InvalidWaitHandle());
       MyTimer = null;
    }
    

提交回复
热议问题