I created a new Windows-Service project and added it to the services using sc.exe, but I am always getting the error when I try to execute the Service.
Code in Program:
static void Main() {
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new Service1()
};
ServiceBase.Run(ServicesToRun);
}
Code in ServiceBase:
public Service1() {
InitializeComponent();
}
protected override void OnStart(string[] args) {
while(true) {
Console.WriteLine("Message all 5 sec...");
Thread.Sleep(5000);
}
}
protected override void OnStop() {
Environment.Exit(0);
}
I tried extending the Timeout in Registry(ServicesPipeTimeout), Using Threads and owning the Service but i still get the error.
Any Help is appreciated.
Kind Regards
CodePudding user response:
Your service will never get out of the onStart-callback because of the endless loop you have created there. So this is blocking and will never finish.
You need to use a timer for your use-case. Just start a timer in your OnStart method and it shall run as expected:
public Service1() {
InitializeComponent();
}
public OnStart(string[] args)
{
Timer timer = new Timer();
timer.Interval = 5000; // 5 seconds
timer.Elapsed = new ElapsedEventHandler(this.OnTimer);
timer.Start();
}
public void OnTimer(object sender, ElapsedEventArgs args)
{
Console.WriteLine("Message all 5 sec...");
}
The timer will send an event every 5 seconds and the added ElapsedEventHandler will call your OnTimer-Method.