Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Windows service doesn't start

I was following this tutorial to create and install a Windows service using Microsoft Visual Studio 2010: http://msdn.microsoft.com/en-us/library/zt39148a%28v=vs.100%29.aspx

I'm using the 3.5 .NET Framework. After several attempts I just created a new service from scratch but this time without providing a method body for the OnStart() method. The service installs successfully, but when I try to run it using the Service Manager, it doesn't do anything and after a while Windows tells me that the service cannot run.

Any kind of help will be greatly appreciate it.

like image 738
David Elizalde Avatar asked Mar 22 '26 15:03

David Elizalde


1 Answers

The OnStart() method is called by the system when the service is started. The method should return as quickly as possible since the system will be waiting for a successful return to indicate that the service is running. Inside this method, you'll typically launch the code that will perform the service's task. This may include starting a thread, starting a timer, open a WCF service host, performing an asynchronous socket command, etc.

Here's a simple example that launches a thread that simply executes an loop that waits for the service to be stopped.

private ManualResetEvent _shutdownEvent;
private Thread _thread;
protected override void OnStart(string[] args)
{
    // Uncomment this line to debug the service.
    //System.Diagnostics.Debugger.Launch();

    // Create the event used to end the thread loop.
    _shutdownEvent = new ManualResetEvent(false);

    // Create and start the thread.
    _thread = new Thread(ThreadFunc);
    _thread.Start();
}

protected override void OnStop()
{
    // Signal the thread to stop.
    _shutdownEvent.Set();

    // Wait for the thread to end.
    _thread.Join();
}

private void ThreadFunc()
{
    // Loop until the service is stopped.
    while (!_shutdownEvent.WaitOne(0))
    {
        // Put your service's execution logic here.  For now,
        // sleep for one second.
        Thread.Sleep(1000);
    }
}

If you've gotten to the point of installing the service, it sounds like you're well on your way. For what it's worth, I've got step-by-step instructions for creating a service from scratch here and follow-on instructions for having the service install/uninstall itself from the command line without relying on InstallUtil.exe here.

like image 122
Matt Davis Avatar answered Mar 25 '26 04:03

Matt Davis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!