McArthey McArthey - 1 month ago 12
C# Question

Windows service only executes once

I've written my first .Net Service using TopShelf and I'm experiencing an issue where the service code only executes a single time.

I have configured the service main as follows

private static void Main(string[] args)
{
HostFactory.Run(x =>
{
x.Service<ServiceProcess>(s =>
{
s.ConstructUsing(name => new ServiceProcess());
s.WhenStarted(tc => tc.Start());
s.WhenStopped(tc => tc.Stop());
});

x.StartAutomatically();
x.RunAs(Username, Password);
});
}


And the method that runs only a single time is as follows.

using System.Timers;

public class ServiceProcess
{
private readonly Timer _timer;

public ServiceProcess()
{
_timer = new Timer(1000) { AutoReset = false };
_timer.Elapsed += (sender, eventArgs) => EventLog.WriteEntry(ServiceName, "It is " + DateTime.Now, EventLogEntryType.Information);
}
}


I can see in the event log that the message is written correctly but it only occurs a single time. Since this is the most basic of configuration I'm not certain why this isn't working. I have played with the timing and attempted to add exception handling but ultimately it appears to simply not be running again.

Note that my
Start()
and
Stop()
methods are doing a
_timer.Start()
and
_timer.Stop()
respectively.

Answer

Set AutoReset property of your timer to true.

Comments