. Net development windows Service summary,. netwindows Summary
Today I learned how to create a windows service under. net. Development Environment: visual studio 2012 I. Program writing (1) Create an empty solution (2) Add a console application project (3) Add a Windows service, as shown below: (4) Right-click the code to view the following code:
public WindowsService(){ InitializeComponent();}protected override void OnStart(string[] args){ }protected override void OnStop(){ }
Here, the OnStart method is executed when the service is started; the OnStop method is executed when the service is stopped; there are two overload Methods: OnPause and OnContinue, which are executed when the service is paused and when the service is restored; they correspond to the following operations:
(5) Add code:
Private Thread timerThread; /// <summary> /// run when the service is started /// </summary> /// <param name = "args"> </param> protected override void OnStart (string [] args) {File. appendAllText ("D: \ 1.txt", DateTime. now. toString ("yyyy-MM-dd HH: mm: ss") + ": windows Service started! \ R \ n ", Encoding. default); timerThread = new Thread (new ThreadStart (Start); timerThread. start () ;}/// <summary> // run when the service is stopped /// </summary> protected override void OnStop () {timerThread. abort (); File. appendAllText ("D: \ 1.txt", DateTime. now. toString ("yyyy-MM-dd HH: mm: ss") + ": End of windows service! ", Encoding. default);} private void Start () {while (true) {using (StreamWriter writer = new StreamWriter ("D: \ 1.txt", true, Encoding. default) {writer. writeLine (DateTime. now. toString ("yyyy-MM-dd HH: mm: ss") + ": output every 10 seconds! ") ;}Thread. Sleep (10*1000 );}}
(6) setup, Set Properties
Add the installer to the designer
A project Installer. cs file is generated, as shown in:
Then we need to do two things:
① Set the Account attribute of the serviceProcessInstaller1 control to "LocalSystem"
② Set the StartType attribute of serviceInstaller1 to Automatic startup and set the service to Automatic startup.
(7) start the service
Run the command prompt tool of vs as an administrator.
Run the following command:
① Enter the project's folder and go to the \ bin \ Debug \ path
② Install the service command installutil ConsoleApplication.exe, And then you can see the service we started in the service list:
Command to uninstall the service: installutil/u ConsoleApplication.exe
After we modify the code, we need to uninstall the service before it can be regenerated successfully.
③ Start the service
After the service is started, wait until the service is stopped. Then, open the 1.txt file under the D Drive. The result is as follows:
Ii. debugging
In the service running status, find the menu bar, debug --> attach to process
Check "display processes of all users", find our processes, click Add, and add breakpoints to the program to debug the program!