tags:

views:

145

answers:

3

What is the best way to run a windows service as a console?

My current idea is to pass in an "/exe" argument and do the work of the windows service, then calling Application.Run().

The reason I'm doing this is to better debug a windows service and allow easier profiling of the code. The service is basically hosting .NET remoted objects.

+3  A: 

The Code Project site had a great article showing how to run a Windows Service in the Visual Studio debugger, no console app needed.

Dour High Arch
+2  A: 

Or

C:\> MyWindowsService.exe /?
MyWindowsService.exe /console
MyWindowsService.exe -console
codemeit
+5  A: 

This is how I do it. Give me the same .exe for console app and service. To start as a console app it needs a command line parameter of -c.

private static ManualResetEvent m_daemonUp = new ManualResetEvent(false);

[STAThread]
static void Main(string[] args)
{
    bool isConsole = false;

    if (args != null && args.Length == 1 && args[0].StartsWith("-c")) {
        isConsole = true;
        Console.WriteLine("Daemon starting");

        MyDaemon daemon = new MyDaemon();

        Thread daemonThread = new Thread(new ThreadStart(daemon.Start));
        daemonThread.Start();
        m_daemonUp.WaitOne();
    }
    else {
        System.ServiceProcess.ServiceBase[] ServicesToRun;
        ServicesToRun = new System.ServiceProcess.ServiceBase[] { new Service() };
        System.ServiceProcess.ServiceBase.Run(ServicesToRun);
    }
}
sipwiz
I ended up with this: ThreadPool.QueueUserWorkItem(state => service.DoWork());new ManualResetEvent(false).WaitOne();I've read that using the ThreadPool is almost always better than explicitly creating threads.
Michael Hedgpeth
Using the ThreadPool is a good idea. I would generally use the ThreadPool ahead of creating a new Thread as well. In the above example I did want more control of the thread for some reason I can't now recall.
sipwiz