question

GerdadeRuiter-7210 avatar image
0 Votes"
GerdadeRuiter-7210 asked karenpayneoregon edited

Why is there never an unsubscribe to match the subscribe to a timer.elapsed event in a service?

When searching for the correct setup of a service in C# which uses a timer,
I noticed that, in all the examples, the subscription to timer.Elapsed event in OnStart(string[] args)
is never matched with a corresponding unsubscribe in OnStop().
Sometimes a timer.Stop(); + timer=null;
but this is never preceded by an unsubscribe.

Why is that?


dotnet-csharp
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

karenpayneoregon avatar image
0 Votes"
karenpayneoregon answered karenpayneoregon edited

In the following example, I dispose the timer then in this code run a job and dispose same as in the first example.

The Timer is initialized with _serviceTimer = new Timer(Dispatcher); which is in this code.

Note This is done with a different Timer from System.Threading.Timer so there is no Elapsed event, see TimerCallback Delegate.


5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.