Monday, January 9, 2017

Console application and windows service in parallel

Windows service is not easy to debug, and sometimes we want our service run as console.

Below sample show how to make console and service work together.

using System;
using System.ComponentModel;
using System.Threading;
using System.ServiceProcess;
using System.Reflection;
namespace ConsoleAndService
{
    class Program
    {

        private static ManualResetEvent _quitEvent = new ManualResetEvent(false);
        static void Main(string[] args)
        {
            ServiceBase[] ServicesToRun;
            ServicesToRun = new ServiceBase[]
            {
                new ConsoleAndService()
            };

            //Run application in console mode, UserInteractive is true.
            //Install service with installutil 
            //Example  InstallUtil /i ConsoleAndService.exe
            //UnInstall InstallUtil /u ConsoleAndService.exe 
            if (!System.Environment.UserInteractive)
            {
                ServiceBase.Run(ServicesToRun);
            }
            else
            {
                Console.CancelKeyPress += (sender, eArgs) => {
                    _quitEvent.Set();
                    eArgs.Cancel = true;
                };
                Type type = typeof(ServiceBase);
                BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic;
                MethodInfo method = type.GetMethod("OnStart", flags);
                foreach (ServiceBase service in ServicesToRun)
                {
                    method.Invoke(service, new object[] { args });
                }
                _quitEvent.WaitOne();
                foreach (ServiceBase service in ServicesToRun)
                {
                    service.Stop();
                }
            }

        }             

    }
}