Michael Hedgpeth
Michael Hedgpeth

Reputation: 7862

Running a windows service in a console

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.

Upvotes: 3

Views: 2447

Answers (3)

sipsorcery
sipsorcery

Reputation: 30699

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);
    }
}

Upvotes: 6

Ray Lu
Ray Lu

Reputation: 26638

Or

C:\> MyWindowsService.exe /?
MyWindowsService.exe /console
MyWindowsService.exe -console

Upvotes: 2

Dour High Arch
Dour High Arch

Reputation: 21711

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

Upvotes: 4

Related Questions