Warning: Cannot modify header information - headers already sent by (output started at /var/www/lalieno.it/index.php:48) in /var/www/lalieno.it/inc/cookie.php on line 3
a cadenza discontinua
Come se fossi
BLOG

[Visual Studio 2013 C# Windows Service] Debug a windows service with visual studio without attacking the process

During the development of a windows service I faced the problem of debugging. Typically to debug you need to "stick" to the process.

However, you can run a debugging from visual studio using the break point with a small trick.

Given that it is service that does not require a user interface, we can make a distinction between running from visual studio and "installed service." This you can do in the Program.cs


static class Program
    {

        static void Main(string[] args)
        { 
            // if userinteractive call in debug mode
            if (Environment.UserInteractive)
            {

                // execute as class with debug true
                new serviceMain(true); 

            }
            else
            {
                //execute  as service
                ServiceBase[] ServicesToRun;
                ServicesToRun = new ServiceBase[] 
                { 
                    new serviceMain(false) 
                };
                ServiceBase.Run(ServicesToRun);
            }
        }
    }

    public partial class serviceMain : ServiceBase
    {
        public serviceMain(Boolean debug)
        {
            InitializeComponent();

            // if debug manual start
            if (debug)
            {
                // manual start
                OnStart(null);
            }
           

        }
        protected override void OnStart(string[] args)
        {
	}
    }

It should be clear enough. Leave comments in doubt.


di GuiZ
23/06/2015

Commenta

We'll never share your email with anyone else.