Home>

Foreword:Microsoft Windows services are capable of creating long-running executable applications in their own windows session.These services can be started automatically when the computer starts,Can be paused and restarted without displaying any user interface.This makes the service very suitable for use on the server,Or at any time,In order not to affect other users working on the same computer,Use when long running function is required.You can also run the service in a security context that is different from the specific user account or the default computer account of the logged-on user.This article will show you how to use c#to create, install, uninstall, and debug windows service programs.

First, create a windows service

1) New windows service project with vs

2) The default generated files include program.cs, service1.cs. Rename service1.cs to your service name or delete service1.cs file and create your own service file,Assume the service name is myservice. Note:If you delete the service1.cs file and then create your own service file,You need to modify service1 in program.cs to myservice.

myservice.cs properties window,The relevant attributes are as follows:

autolog whether to automatically write to the system's log file

canhandlepowerevent Receive power event when service

canpauseandcontinue Whether the service accepts requests to pause or resume

canshutdown Whether the service is notified when the computer running it is shut down,To be able to call the onshutdown procedure

canstop service accepts requests to stop running

servicename service name

note:The default values ​​of both canpauseandcontinue and canshutdown are false. To make the service's onpause (), oncontinue (), and onshutdown () work, you need to set the values ​​of cancelandcontinue and canshutdown to true.

3) Double-click the myservice.cs service file,In the left design mode,Right-click "Add Installer" (or click "Add Installer" below the properties window of myservice.cs;if you don't see the clickable link for "Add Installer",You can right-click the properties window,Click "Command (c)" and it will come out.Note:it is the properties window instead of the file properties window), the projectinstaller.cs file and two installation components are automatically generated,as follows:

4) Click "serviceprocessinstaller1" and set the account account method in its properties window,It is recommended to be localservice (of course, the account attribute can also be changed to localsystem, so no matter which system the user is logged into,The service will always start).

5) Click "serviceinstaller1" and set properties in its properties window:

A) description service description,Display the description directly in the windows service list;

B) displayname service display name,The name displayed directly in the windows service list;

C) servicename service process name,Unique ID when installing and uninstalling services.

The specific settings are shown in the figure above.

6) Create install service batch file install.bat, you can create Notepad,Then modify the suffix to bat, the contents of Notepad are as follows:

%systemroot%\ microsoft.net \ framework \ v4.0.30319 \ installutil.exewindowsservicedemo.exe

net startmyservice

sc config myservicestart=auto

pause

note:Set the encoding to ansi when saving Notepad as

Explanation:The second line starts the service,The third line sets the service to run automatically,These two lines choose their own service style.If you need to see the script health,Add pause in the last line of the script.

7) Similarly, create the uninstall service batch file uninstall.bat with the following contents:

%systemroot%\ microsoft.net \ framework \ v4.0.30319 \ installutil.exe /uwindowsservicedemo.exe

pause

8) Add the two files install.bat and uninstall.bat to the bin \ debug directory. At this time, the directory structure of the solution is as follows:

9) write the service code,Take the time of writing a text record system to a text file as an example:

using system;
using system.io;
using system.diagnostics;
using system.serviceprocess;
using system.timers;
namespace windowsservicedemo
{
 public partial class myservice:servicebase
 {
 private timer time=new timer ();
 public myservice ()
 {
 initializecomponent ();
 }
 protected override void onstart (string [] args)
 {
 #if debug
 if (! debugger.isattached)
 debugger.launch ();
 debugger.break ();
 #endif
 writelog ("service started,Time:"+ datetime.now.tostring (" hh:mm:ss ") +" \ r \ n ");
 time.elapsed +=new elapsedeventhandler (methodevent);
 time.interval=60 * 1000;//time interval is 2 seconds
 time.start ();
 }
 protected override void onstop ()
 {
 #if debug
 if (! debugger.isattached)
 debugger.launch ();
 debugger.break ();
 #endif
 writelog ("service stopped,Time:"+ datetime.now.tostring (" hh:mm:ss ") +" \ r \ n ");
 }
 protected override void onpause ()
 {
 #if debug
 if (! debugger.isattached)
 debugger.launch ();
 debugger.break ();
 #endif
 writelog ("Service suspended,Time:"+ datetime.now.tostring (" hh:mm:ss ") +" \ r \ n ");
 base.onpause ();
 }
 protected override void oncontinue ()
 {
 #if debug
 if (! debugger.isattached)
 debugger.launch ();
 debugger.break ();
 #endif
 writelog ("Service resumed,Time:"+ datetime.now.tostring (" hh:mm:ss ") +" \ r \ n ");
 base.oncontinue ();
 }
 protected override void onshutdown ()
 {
 writelog ("The computer is off,Time:"+ datetime.now.tostring (" hh:mm:ss ") +" \ r \ n ");
 base.onshutdown ();
 }
 private void methodevent (object source, system.timers.elapsedeventargs e)
 {
 time.enabled=false;
 string result=string.empty;
 try
 {
 //.........
 result="Successful execution,Time:"+ datetime.now.tostring (" hh:mm:ss ") +" \ r \ n ";
 }
 catch (exception ex)
 {
 result="The execution failed.
Reason:"+ ex.message +" \ r \ n ";
 }
 finally
 {
 writelog (result);
 time.enabled=true;
 }
 }
 ///<summary>
 ///log record
 ///</summary>
 ///<param name="loginfo"></param>
 private void writelog (string loginfo)
 {
 try
 {
 string logdirectory=appdomain.currentdomain.basedirectory + "\\ logs";
 if (! directory.exists (logdirectory))
 {
  directory.createdirectory (logdirectory);
 }
 string filepath=logdirectory + "\\" + datetime.now.tostring ("yyyy-mm-dd") + ".txt";
 file.appendalltext (filepath, loginfo);
 }
 catch
 {
 }
 }
 }
}

note:After writing the code,You can't click on the start button or press f5 to run or debug the service,The warning shown below will pop up:

Second, install the windows service

After the project is successfully generated,Navigate to the bin \ debug directory and run the install.bat installation service as an administrator.The successful results are as follows:

At this time, right-click "My Computer", select "Manage", and select "Services" under "Services and Applications", you can see that the service is installed,As shown below:

At the same time, there is a logs folder in the debug folder, and a txt file in the logs folder, as follows:

can be seen,Executed every minute.

Third, debug the windows service

1) The usual solution is,After the service is running, select "Attach to Process" in the debugger and attach your own service to debug.But this method has limitations.For example, the code in the onstart event when the service starts, Basically difficult to debug,Often when attaching to our service, this part of the code has already been executed.Of course, you can let sleep for 20s before the onstart event, and "attach to the process" while the service is sleeping. system.threading.thread.sleep (1000 * 20);

2) My approach is,Add "debugger.launch ();" to the beginning of the onstart event. When the service runs here,A dialog box for selecting the debugger will pop up,At the same time pause at the current position.In this way, we can manually start the debugger in the code.

Explanation:a) The function of debugger.launch () is to "start the debugger and connect it to the process";

B) can set breakpoints manually,You can also use "debugger.break ();" to set breakpoints dynamically;

C) To avoid multiple debugger instances,You can use the "debugger.isattached" property to determine whether the debugger is attached to the process,code segment:

if (! debugger.isattached) debugger.launch ();

D) In ​​order to make debugging effective only in debug mode,Invalid in release mode,Can be handled with conditional compilation,The code snippet is as follows:

#if debug
 if (! debugger.isattached)
 debugger.launch ();
 debugger.break ();
 #endif

About conditional compilation,Check out my other blog:c#-#define conditional compilation

E) When debugging other events or methods of the service,Can also be used.

A dialog box for selecting a debugger pops up,And the debugging interface is shown below:

Fourth, uninstall the windows service

Uninstall service,You can also run uninstall.bat as an administrator. The successful result is as follows:

c
  • Previous Set the MySQL automatic growth method to start from a specified number
  • Next Android four methods to get the screen width summary