Run Windows Service as a console Program

Source: Internet
Author: User
ArticleDirectory
    • Update: 16.08.2007

 

Visual Studio and. net Framework make it really easy to create Windows Services. all you have to do is create a new project, select 'windows service' as your project type and you're all set. however, debugging Windows Services in Visual Studio can be a big pain. the recommended way is to use installutil to install them, and then restart the service and attach the debugger everytime you want Debug it. I wanted Windows Live! BOT to be available as a Windows service, but I also wanted to be able to debug it without the hassystemic, so here's what I came up:


   Using System;
Using System. serviceprocess;

Public   Partial   Class Demoservice: servicebase
{
Static   Void Main ( String [] ARGs)
{
Demoservice Service =   New Demoservice ();

If (Environment. userinteractive)
{
Service. onstart (ARGs );
Console. writeline ( " Press any key to stop program " );
Console. Read ();
Service. onstop ();
}
Else
{
Servicebase. Run (service );
}

}
Public Demoservice ()
{
Initializecomponent ();
}

Protected   Override   Void Onstart ( String [] ARGs)
{
// Todo: Add code here to start your service.
}

Protected   Override   Void Onstop ()
{
// Todo: Add code here to perform any tear-down
// Necessary to stop your service.
}
}

This will allow you to use your program as either a normal console program or a Windows service, with no special builds, # debug directives, command line parameters or anything like that. what it does is in the main method it checks the 'environment. userinteractive 'Property. this will be true when it is run from Visual Studio, or when you just click on. EXE file, but false if it's being run as a service. when it's run from Visual Studio or as a standalone program it will keep running until you press a key, then it will call your onstop method and then terminate.

Two things to watch out:

    1. You'll have to right click on your project in Visual Studio, choose Properties and select the output type as 'console application' for this to work.
    2. If your main method is not in your service class, you'll have to add public methods to your class that can start and stop it, for instance AddPublic void startconsole (string [] ARGs)That just callyour onstart, since onstart and onstop are protected methods and as such not accessible from other classes.
Update: 16.08.2007

Reader Anderson IMES (who has a rather nice debugging solution of his own) pointed out some things to fix. one thing is that a Windows service can run startup services in the same process, the servicebase. run method can take an array of servicebase objects. I still think that the code above is the best way to do it if you have just a single service, just keep the main method in the service class. but if you 've got multiple service objects then That doesn' t make sense anymore, we want to put our main method somewhere else. and then we have the problem of not being able to call onstart in the service objects, since it's a protected method. we cocould define a public startconsole method in all of them that callthe onstart method like I described above, but that will get tiresome if you have created objects. well, there is another way to do it with reflection which I 've written here below. the new Code is basically the same as the first version, doesn't that it has an array of servicebase objects, called servicestorun, and loops through it, calling each object's onstart method through some neat reflection tricks. when the user presses a button it will stop all services by calling their stop method, which in turn callthe onstop method that all services must define.


   Using  System. serviceprocess;
Using System;
Using System. reflection;

Static   Class Program
{
Static   Void Main ( String [] ARGs)
{
Servicebase [] servicestorun =   New Servicebase [] { New Service1 ()
, New Service2 ()
, New Service3 ()};

If (Environment. userinteractive)
{
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 });
}

Console. writeline ( " Press any key to exit " );
Console. Read ();

Foreach (Servicebase Service In Servicestorun)
{
Service. Stop ();
}

}
Else
{< br> servicebase. run (servicestorun);
}< BR >}< br>

while using this trick has worked perfectly well for my services, which have all been pretty simple, it might not work for everyone. i'm sure there are a few things different between Windows Services and console programs that I don't know about, and might make the console version of the program behave strangely in some cases. imes also pointed out that there was no way to test pause-and-resume in the console version. the best way I cocould think of to mimic service events like these wocould be to read in keypresses in the main thread and do the appropriate action depending on the key pressed. for instance, instead of the "press any key to exit" message, we might have "Press P to pause, R to resume, s to stop" and then the result of console. read () cocould be used to determine which action to take and which methods to call on the service objects. however, I don't have the time and interest to do it right now, So implementing it is left as an exercise for the reader.

 

From: http://tech.einaregilsson.com/2007/08/15/run-windows-service-as-a-console-program/

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.