Search code examples
c#windowswindows-services

Why does my Windows Service automatically quit after approx 5 secs?


I've create a Windows Service using C# that when OnStart is called creates a new thread from another class. This new thread then loops waiting for any incoming TCP connections. Or it should. When I start the service it automatically stops after about 5 seconds. I don't know why it is doing this. I understand that services close on their own if they have no work to do but the work has been specified for it. Anyone got any ideas why this would be happening? My OnStart Method looks like this:

protected override void OnStart(string[] args)
    {
        Thread thread = new Thread(new StateMachine().AcceptConnections);
        thread.Start();      
    }

Which then calls this method:

        Int32 port = 13000;
        IPAddress localAddr = IPAddress.Parse("127.0.0.1");

        server = new TcpListener(localAddr, port);

        // Start listening for client requests.
        server.Start();
        // Enter the listening loop.
        do
        {
            client = server.AcceptTcpClient();
            ReceivedData();                
        } while (true);
    }

It does not stay on long enough to allow any clients to connect to the TcpListner.

Help?


Solution

  • Firstly, are you sure you want your service to spawn a new thread to do this? You can't simply do it on the main thread?

    To debug your problem, do one or both of the following:

    1. Add some logging, either using the EventLog or a logging framework (Log4Net).
    2. Run your service as a console app and debug it in Visual Studio