Friday, April 29, 2011

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.

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

  • Or

    C:\> MyWindowsService.exe /?
    MyWindowsService.exe /console
    MyWindowsService.exe -console
    
  • 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);
        }
    }
    
    Michael Hedgpeth : 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.
    sipwiz : 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.

0 comments:

Post a Comment