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 di un servizio windows con visual studio senza attaccare il processo

Durante lo sviluppo di un servizio windows ho dovuto affrontare la problematica del debug. In genere per eseguire il debug è necessario "attaccarsi" al processo.

E' però possibile eseguire un debug da visual studio utilizzando i break point con un picolissimo stratagemma.

Dato che si tratta di service, che non richiede un interfaccia utente, possiamo eseguire una distinzione tra l'esecuzione da visual studio e da "servizio installato". Questo è possibile farlo nella 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)
        {
	}
    }

Dovrebbe essere tutto abbastanza chiaro. Lasciate commenti nel caso di dubbi.


di GuiZ
23/06/2015

Commenta

We'll never share your email with anyone else.