McArthey McArthey - 3 years ago 119
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.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
methods are doing a

Answer Source

Set AutoReset property of your timer to true.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download