C# – Windows service stops automatically


I made a Window service and let it work automatically and under localsystem account, when the service starts it fires this message for me and then stops

The [service name] service on local computer started and then stopped. Some Services stop automatically if they are not in use by another services or programs.

What's the problem and what's the solution?

Best Answer

Either you are not starting any threads on the OnStart method to do work, or there is an exception raised within your OnStart method.

If an exception is thrown, it will appear in the Windows Event log. The Windows Event log is a good place to start in any case.

Generally an OnStart method looks like this:

Thread _thread;

protected override void OnStart(string[] args)
    // Comment in to debug
    // Debugger.Break()

    // Do initial setup and initialization

    // Kick off a thread to do work
    _thread = new Thread(new MyClass().MyMethod)

    // Exit this method to indicate the service has started