C # simple tutorial on creating, installing, uninstalling, and debugging Windows Service,

Source: Internet
Author: User

C # simple tutorial on creating, installing, uninstalling, and debugging Windows Service,

Preface: Microsoft Windows Services can create executable applications that can run for a long time in their own Windows sessions. These services can be automatically started when the computer is started. They can be paused and restarted without displaying any user interface. This makes the service very suitable for use on the server, or any time, in order not to affect other users working on the same computer, it needs to be used for a long time to run the function. You can also run the service in a security context different from the logon user's specific user account or default computer account. This article describes how to use C # To create, install, uninstall, and debug Windows Service programs.

1. Create a Windows Service

1) Use VS to create a Windows Service Project

2) by default, generated files include Program. cs and Service1.cs. Rename Service1.cs to your service name or delete the Service1.cs file and create your own service file. Assume that the service name is MyService. Note: If you want to delete the Service1.cs file and create your own service file, you need to change Service1 in the Program. cs file to MyService.

In the MyService. cs Properties window, the related properties are as follows:

Whether Autolog is automatically written to the System Log File
Receive Power Events During CanHandlePowerEvent Service
Whether the CanPauseAndContinue Service accepts the pause or continue running request
Whether the CanShutdown Service receives a notification when the computer that runs it shuts down, so that it can call the OnShutDown Process
Whether the CanStop Service accepts the stop operation request
ServiceName service name

Note: The default values of CanPauseAndContinue and CanShutdown are both False. To enable OnPause (), OnContinue (), and OnShutdown () of the service, set the value of CanPauseAndContinue and CanShutdown to True.

3) double-click MyService. cs service file. In Design Mode on the left, right-click "add installer" (or in MyService. click "add installer" at the bottom of the cs Properties window. If you cannot see the "add installer" link, right-click the Properties window and click "command (C). Note: The Projectinstaller. cs file and two installation components are automatically generated, as shown in the following figure:

4) Click "serviceProcessInstaller1" and set the Account method in its Properties window. It is recommended to set it to LocalService (of course, you can change the Account attribute to LocalSystem. In this way, no matter which user is logged on to the system, the Service will always start ).

5) Click "serviceInstaller1" and set properties in Its Properties window:

A) Description service Description, which is directly displayed in the Windows Service list;

B) display name of the DisplayName service, which is directly displayed in the Windows Service list;

C) Name of the ServiceName service process, which is the unique identifier used to install and uninstall the service.

Shows the specific settings.

6) Create and Install the service batch file Install. bat. You can create a notepad and modify the suffix to bat. The content of the notepad is as follows:

% SystemRoot % \ Microsoft. NET \ Framework \ v4.0.30319 \ installutil.exe WindowsServiceDemo.exe
Net Start MyService
SC config MyService start = auto
Pause

Note: When saving notepad as a file, set the encoding to ANSI.

Note: The second action starts the service, and the third Action sets the service to run automatically. The two rows are selected based on the service form. To view the script running status, add pause to the last line of the script.

7) Similarly, the unmount service batch file Uninstall. bat is created. The content is as follows:

% SystemRoot % \ Microsoft. NET \ Framework \ v4.0.30319 \ installutil.exe/u WindowsServiceDemo.exe
Pause

8) Add the Install. bat and Uninstall. bat files to the bin \ Debug directory. the directory structure of the solution is as follows:

 

9) Write service code. Take the system time for writing text records to text files as an example:

1 using System; 2 using System. IO; 3 using System. diagnostics; 4 using System. serviceProcess; 5 using System. timers; 6 7 namespace WindowsServiceDemo 8 {9 public partial class MyService: ServiceBase 10 {11 private Timer time = new Timer (); 12 public MyService () 13 {14 InitializeComponent (); 15} 16 17 protected override void OnStart (string [] args) 18 {19 # if DEBUG 20 if (! Debugger. isAttached) 21 Debugger. launch (); 22 Debugger. break (); 23 # endif 24 WriteLog ("service start, time:" + DateTime. now. toString ("HH: mm: ss") + "\ r \ n"); 25 time. elapsed + = new ElapsedEventHandler (MethodEvent); 26 time. interval = 60*1000; // The Interval is 2 seconds and 27 times. start (); 28} 29 30 protected override void OnStop () 31 {32 # if DEBUG 33 if (! Debugger. isAttached) 34 Debugger. launch (); 35 Debugger. break (); 36 # endif 37 WriteLog ("Service stopped, time:" + DateTime. now. toString ("HH: mm: ss") + "\ r \ n"); 38} 39 40 protected override void OnPause () 41 {42 # if DEBUG 43 if (! Debugger. isAttached) 44 Debugger. launch (); 45 Debugger. break (); 46 # endif 47 WriteLog ("service suspension, time:" + DateTime. now. toString ("HH: mm: ss") + "\ r \ n"); 48 base. onPause (); 49} 50 51 protected override void OnContinue () 52 {53 # if DEBUG 54 if (! Debugger. isAttached) 55 Debugger. launch (); 56 Debugger. break (); 57 # endif 58 WriteLog ("service recovery, time:" + DateTime. now. toString ("HH: mm: ss") + "\ r \ n"); 59 base. onContinue (); 60} 61 62 protected override void OnShutdown () 63 {64 WriteLog ("Computer disabled, time:" + DateTime. now. toString ("HH: mm: ss") + "\ r \ n"); 65 base. onShutdown (); 66} 67 68 private void MethodEvent (object source, System. timers. elapsedEventArgs e) 69 {70 time. enabled = false; 71 string result = string. empty; 72 try 73 {74 //......... 75 result = "execution successful, time:" + DateTime. now. toString ("HH: mm: ss") + "\ r \ n"; 76} 77 catch (Exception ex) 78 {79 result = "execution failed, cause: "+ ex. message + "\ r \ n"; 80} 81 finally 82 {83 WriteLog (result); 84 time. enabled = true; 85} 86} 87 // <summary> 88 // log 89 // </summary> 90 // <param name = "logInfo"> </param> 91 p Rivate void WriteLog (string logInfo) 92 {93 try 94 {95 string logDirectory = AppDomain. CurrentDomain. BaseDirectory + "\ Logs"; 96 if (! Directory. exists (logDirectory) 97 {98 Directory. createDirectory (logDirectory); 99} 100 string filePath = logDirectory + "\" + DateTime. now. toString ("yyyy-MM-dd") + ". txt "; 101 File. appendAllText (filePath, logInfo); 102} 103 catch104 {105 106} 107} 108}
System time for writing text records to text files

Note: After the code is compiled, you cannot click the start button or press F5 to run or debug the service. The warning shown in is displayed:

II,Install windows Services

After the project is successfully generated, go to the bin \ Debug directory and run Install. bat as an administrator to Install the service. The successful result is as follows:

 

In this case, right-click "my computer", select "manage", and select "service" under "services and applications" to see that the service has been installed, for example:

At the same time, the Debug folder contains the Logs folder and the Logs folder contains the txt file, the content is as follows:

We can see that the task is executed once every minute.

Iii. debug windows Services

1) The common solution is to select "attach to process" in the debugger after the service is running, and then attach your own service to debug. However, this method has limitations. For example, the code in the OnStart event during service startup is basically difficult to debug. When attach arrives at our service, this part of the Code has already been executed. Of course, you can let the OnStart event first go to bed for 20 s, and "attach to the process" as the service goes to bed ". System. Threading. Thread. Sleep (1000*20 );

2) My approach is to add "Debugger. launch (); "is called. when the service is running here, a dialog box for selecting the debugger will pop up and paused at the current position. In this way, we can manually start the debugger in the code.

Note: a) the role of the Debugger. Launch () method is to "Start the Debugger and connect it to the process ";

B) You can manually set breakpoints, or use "Debugger. Break ();" to dynamically set breakpoints;

C) to avoid multiple Debugger instances, you can use the "Debugger. IsAttached" attribute to determine whether the Debugger has been attached to a process. code snippet: if (! Debugger. IsAttached) Debugger. Launch ();

D) for debugging to take effect only in Debug mode, the Release mode is invalid and can be processed using Conditional compilation. The code snippets are as follows:

 #if DEBUG if (!Debugger.IsAttached)     Debugger.Launch(); Debugger.Break(); #endif

For Conditional compilation, check my other blog: C #-# define Conditional compilation.

E) It can also be used when debugging other events or methods of the service.

The Select debugger dialog box is displayed, as shown in the following figure:

 

IV,Uninstall windows Services

Uninstall the service and run Uninstall. bat as an administrator. The successful result is as follows:

Reference link: https://msdn.microsoft.com/zh-cn/library/windows/desktop/system.diagnostics.debugger (v = vs.110). aspx

Download source code: WindowsServiceDemo.rar

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.