Forum Discussion
AharonBensadoun
Nov 09, 2021Copper Contributor
How to add a timer to C# Service
Hi everyone I am new to coding in c # and trying to write a windows service in c #, my service seems to be working fine except for one thing: I try to make it run in a loop, say every 30 seconds, a...
IFYates
Nov 09, 2021Copper Contributor
I can't build a test right now, but my first thought is that the issue is that your Main is completing (there's nothing holding the main thread). *
Instead of an event-based timer, why not use Task-based asynchronous code.
Not tested, but something like:
async static Task Main()
{
while (isRunning) // A token or flag to hold the application running until the service is stopped
{
// do work
await Task.Delay(sleepTimeInMs);
}
}
Also, your OnStart and OnStop methods are extremely similar; I would look at taking the shared code to a function (e.g., runPowershellScript).
* RobIII is definitely more correct on this point. The issue is that your Timer is no longer referenced at the end of Main, so is being collected.
I assume the service continues to say it's running, as it's life-cycle managed by SCM.
Regardless, my suggestion is one way to solve it.