C # Windows Service Service creation and debugging

Source: Internet
Author: User
Tags dateformat

Objective

Articles about Windows service creation and debugging are available in many articles on the web, and it's just a record that doesn't make people more impressed. Therefore, in order to better understand the service project creation and commissioning process and methods for the purpose, with this record.

Directory

What is a Windows service service? II. C #-based Windows Service Service creation, installation, uninstallation? third, how to debug the code during the development of Windows service service?

Body

What is a Windows service service? Microsoft Windows Services (that is, previous NT services) enable you to create executable applications that can run for long periods of time in their own Windows sessions. These services can be started automatically when the computer starts, can be paused and restarted, and does not display any user interface. This makes the service ideal for use on the server, or at any time, in order not to affect other users working on the same computer, which requires long-running functionality. You can also run a service in a different security context than a specific user account or a default computer account that is a logged-on user. (Baidu Encyclopedia) II. C #-based Windows Service Service creation, installation, uninstallation? 1. Open: Visual Studio + + new + + project + Windows Services, step: 3. Set the project name 4. Set the project folder where the disk is located 2, rename the Service1.cs file name is easy to identify The file name, here I renamed to MyFirstWinService.cs.     Right-click in the Design view of this file and choose Add Installer from the pop-up menu.       3, the project will automatically generate the installation file ProjectInstaller.cs, and set the properties of ServiceIntaller1 and ServiceProcessInstaller1, respectively.   Here, the installer and the framework for the service have been built, and then you can write your own business code in the Code view of the service class MyFirstWinService.cs, as in the following code. 4, the service class MyFirstWinService.cs within the code
1 usingSystem;2 usingsystem.serviceprocess;3 4 namespacewindowsservicetest5 {6      Public Partial classMyfirstwinservice:servicebase7     {8          PublicMyfirstwinservice ()9         {Ten InitializeComponent (); One         } A  -         protected Override voidOnStart (string[] args) -         { the             stringstr ="Service Open"; -Testclass.writemsgtofile (@"E:\MyProjects\WSExample.txt", str +", Time:"+ DateTime.Now.ToString ("YYYY-MM-DD HH:mm:ss")); -         } -  +         protected Override voidOnStop () -         { +             stringstr ="Service stopped"; ATestclass.writemsgtofile (@"E:\MyProjects\WSExample.txt", str +", Time:"+ DateTime.Now.ToString ("YYYY-MM-DD HH:mm:ss")); at         } -  -         protected Override voidOnContinue () -         { -             stringstr ="Service continues to run"; -Testclass.writemsgtofile (@"E:\MyProjects\WSExample.txt", str +", Time:"+ DateTime.Now.ToString ("YYYY-MM-DD HH:mm:ss")); in         } -  to         protected Override voidOnPause () +         { -             stringstr ="Service suspended"; theTestclass.writemsgtofile (@"E:\MyProjects\WSExample.txt", str +", Time:"+ DateTime.Now.ToString ("YYYY-MM-DD HH:mm:ss")); *         } $     }Panax Notoginseng  -      Public Static classTestClass the     { +          Public Static voidWritemsgtofile (stringFileName,stringcontent) A         { the             using(System.IO.StreamWriter SW =NewSystem.IO.StreamWriter (FileName,true)) +             { - SW. WriteLine (content); $             } $         } -     } -}
View Code5, in the above steps, has completed the service development work. The next step is the installation process of the service: 1) cmd command to install the service:%systemroot%\microsoft.net\framework\v4.0.30319\installutil.exe WindowsServiceTest.exe 2) The cmd command to uninstall the service:%systemroot%\microsoft.net\framework\v4.0.30319\installutil.exe/u WindowsServiceTest.exe But here, I write the command operation as two batch files: Install.bat
%systemroot%\microsoft.net\framework\v4.0.30319\installutil.exe windowsservicetest.exenet Start ServiceTest
Uninstall.bat
net stop servicetest%systemroot%\microsoft.net\framework\v4.0.30319\installutil.exe/u WindowsServiceTest.exe
Put the batch file under the project's Bin->debug folder, which makes it easy to install and uninstall the service. Of course, written as a batch file, it is also convenient to use Program Control Service installation and uninstallation. third, how to debug the code during the development of Windows service service? For beginners with a certain C # base, it is relatively easy to create and complete a simple service program using Visual Studio. But it's still a bit cumbersome to debug Windows service programs.  The main thing is that the Windows Service program has no way to set breakpoints directly inside the code like other Windows programs, and press F5 to start code debugging. After finding the data and debugging in person, three methods are obtained: Method 1: Write Log
This is the most traditional debugging method, but also a lot of program development debugging code is very common. It's just that this method can't see the changes in the code in real time, but only add the log to the place where you think it might be wrong, and record the data change process. Method 2: Attach the process
This is a common debugging method for Windows service development. This method must first compile the well-written service to build the executable EXE installer, and install the start-up service before you can attach the service process.
1, first to install the service, and then start the service.
2. Open the VS Project, select Menu Debug, attach to process options, select your service process (if you can't find the show all user processes option). For example, there is a problem: The OnStart function has been executed while attaching to the process, so the OnStart cannot be debugged. This can be done by setting the start service delay to load debugging.
        PrivateSystem.Timers.Timer Timerdelay; protected Override voidOnStart (string[] args) {            Try            {                ///delay Start the syndata 30secondsTimerdelay =NewSystem.Timers.Timer (30000); Timerdelay.elapsed+=NewSystem.Timers.ElapsedEventHandler (timerdelay_elapsed);            Timerdelay.start (); }            Catch(Exception ex) { This.            Printexceptions (ex); }        }        voidTimerdelay_elapsed (Objectsender, System.Timers.ElapsedEventArgs e) {timerdelay.enabled=false;                        Timerdelay.close (); //the code you want to add            stringstr ="Service Open"; Testclass.writemsgtofile (FilePath, str+", Time:"+DateTime.Now.ToString (DateFormat)); }
View Code    Note: Normal service start time is about 30 seconds, when the service start time more than 30 seconds will be an error! , so do not do too much in the onstart, or you can start the service with this time-lapse method in case the service is started. Method 3: Modify the start code in the main function
This is a trickery method, in the main function, comment out the original automatically generated code, manually instantiate the written service class. The red part of the following code: Static Class Program
{
<summary>
The main entry point for the application.
</summary>
static void Main ()
{
Servicebase[] ServicesToRun;
ServicesToRun = new servicebase[]
//{
New Servicetest ()
//};
Servicebase.run (ServicesToRun);

Servicetest st = new Servicetest ();//servicetest service class built for himself
St. OnStart ();
}
You then need to modify the protected override void OnStart (string[] args) in the Servicetest class to public void OnStart (), and then you can set breakpoints in the OnStart () method,        Press F5 to run the Debug. public void OnStart ()
{
String str = "Service open";
Testclass.writemsgtofile (FilePath, str + ", Time:" + DateTime.Now.ToString (DateFormat));
Code Something ...
The other methods in the Servicetest class can be debugged in this way, and when the debugging is complete, the method is modified back to the original look. Add:1) Service startup properties: After the Manual services are installed, they must be started manually.    Automatic the service will start automatically every time the computer restarts. The Disabled service could not be started. 2) New service project with the meanings of each attribute (service class MyFirstWinService.cs Design view, right-click Property): Autolog is automatically written to the system's log file Canhandlepowerevent The Power event CanPauseAndContinue whether the service accepts a pause or a request to continue running CanShutdown The service is notified when the computer on which it is running is closed so that it can invoke the OnShutdown process CanStop the service is    Do not accept a request to stop running ServiceName Service Name 3) also available in System Service Manager, set the properties of the corresponding service or startup method, such as Computer Management, services and applications, etc... These are just the debugging methods I now know, and of course, there are times when you need a combination of methods to debug.

C # Windows Service Service creation and debugging

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.