views:

102

answers:

4

Scenario

I've created a windows service, but whenever I start it, it stops immediately. The service was concieved from a console application that used to subscribe to an event and watch processes on a server. If anything happened to process (i.e. It was killed), then the event would trigger the process to be restarted. The reason I'm telling you this is because the original code used to look like this:

Original Console App Code:

    static void Main(string[] args)
    {
        StartProcess sp = new StartProcess();
        //Note the readline that means the application sits here waiting for an event!
        Console.ReadLine(); 
    }

Now that this code has been turned into a Windows Service, it is essentially EXACTLY THE SAME. However, the service does not sit there waiting, even with the readline, it just ends.....

New Windows Service Code:

    protected override void OnStart(string[] args)
    {
        ProcessMonitor pm = new ProcessMonitor();
        Console.ReadLine();
    }

Thoughts

Since the functionality is entirely encapsulated within this single class (It quite literally starts, sets up some events and waits) - How can I get the service to actually sit there and just wait? It seems to be ignoring the readline. However this works perfectly as a console application, it is just far more convenient to have it as a service.

+3  A: 

In a Service there is no concept of a readline - there's no keyboard. I wouldn't be surprised if this is throwing an exception at that call. Have you checked your Application Log?

qor72
+2  A: 

Well... A service doesn't have a console input/output. So the ReadLine won't stop it from executing.

What does ProcessMonitor do?

Typically, for services your code lives in a thread that monitors whether the service has been stopped or paused.

Chris Lively
A: 

OnStart() must complete and end successfully for the service to be considered "Started"

Lucas B
Please don't. Services should *never* open a window (One exception maybe being Window's DcomLaunch service) as they are running in a non-interactive session and are isolated from any GUI session.
0xA3
I agree, removing line.
Lucas B
+5  A: 

Typically you would want something like this. As Joe mentioned in the comments you want Start to initialize and release control to another thread to make sure that you return within 30 seconds.

private readonly ProcessMonitor processMonitor = new ProcessMonitor();

protected override void OnStart(string[] args)
{
    processMonitor.Start();
}

protected override void OnStop()
{
    processMonitor.Stop();
}
ChaosPandion
processMonitor.Start() needs to return though; OnStart has ~30 seconds to start up successfully.
Joe
@Joe - An important detail :)
ChaosPandion