Windows Service System.Timers.Timer not firing

前端 未结 6 1911
走了就别回头了
走了就别回头了 2020-12-05 04:36

I have a Windows service written in C# which is meant to perform a task every few minutes. I\'m using a System.Timers.Timer for this but it doesn\'t ever appea

6条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-05 05:02

    Apparently, System.Timers.Timer hides any exceptions, swallows them quietly, and then chokes. Of course, you can handle these in your method that you've added as a handler to your timer, but if the exception is thrown immediately on entrance (before the first line of code is executed, which can happen if your method declares a variable that uses an object in a strong-named DLL of which you have the wrong version, for instance), you are never going to see that exception.

    And you are going to join us all in tearing your hair out.

    Or you could do this:

    • create a wrapper method that (in a try-catch loop) calls the method you would like to have executed. If this method is dying on you, the wrapped method can do the exception handling, without killing the timer, because if you do not stop the timer, it will never notice something went wrong.

    (I did end up stopping the timer, because if it fails, trying again makes no sense for this particular application...)

    Hope this helps those who landed here from Google (as did I).

提交回复
热议问题