3

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.

Matt Davis
  • 45,297
  • 16
  • 93
  • 124
  • 1
    If the `OnStart` method does nothing, the service will exit immediately. Typically, a service will start some foreground thread to keep things going. – Matt Davis Dec 28 '13 at 19:34

2 Answers2

1

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.

Community
  • 1
  • 1
Matt Davis
  • 45,297
  • 16
  • 93
  • 124
0

I finally managed to solve the issue. Apparently the problem lies in the Visual Studio installer, since i managed to compile the project and then install the service using installutil on administrative mode.