Today I learned to create a Windows service under. NET and summarize your learning experience. Development environment: Visual Studio 20,121, authoring Program (1) Create an empty workaround (2) Add a console Application project (3) Add a Windows service as follows: (4) Right-click the code to see the following code:
Public Windowsservice () { InitializeComponent ();} protected Override void OnStart (string[] args) { }protectedoverridevoid OnStop ( ){ }
Where the OnStart method executes when the service is started, the OnStop method executes when the service is stopped, and two overloaded methods: OnPause, OnContinue, are executed when the service is paused, and when the service is resumed; they correspond to the actions shown:
(5) Add code:
PrivateThread TimerThread;/// <summary>///Execute when service is started/// </summary>/// <param name= "args" ></param>protected Override voidOnStart (string[] args) {File.appendalltext ("D:\\1.txt", DateTime.Now.ToString ("YYYY-MM-DD HH:mm:ss") +": Windows service starts to work! \ r \ n", Encoding.default); TimerThread=NewThread (NewThreadStart (Start)); Timerthread.start ();}/// <summary>///Execute when service is stopped/// </summary>protected Override voidOnStop () {timerthread.abort (); File.appendalltext ("D:\\1.txt", DateTime.Now.ToString ("YYYY-MM-DD HH:mm:ss") +": Windows service finishes working! ", Encoding.default);}Private voidStart () { while(true) { using(StreamWriter writer =NewStreamWriter ("D:\\1.txt",true, Encoding.default)) {writer. WriteLine (DateTime.Now.ToString ("YYYY-MM-DD HH:mm:ss") +": Output every 10 seconds! "); } thread.sleep (Ten* +); }}
(6) Installation program, setting properties
To add a setup program in the designer
A ProjectInstaller.cs file is generated, as shown in:
Then you need to do two things:
① Setting the Account property of the ServiceProcessInstaller1 control to "LocalSystem"
② set the StartType property of the ServiceInstaller1 component to Automatic, set the service to start automatically
(7) Start-up service
Open vs Developer Command prompt tool run as Administrator
Execute the command shown below:
① go to the folder where the project is located and enter the \bin\debug\ path
② Install service command: InstallUtil ConsoleApplication.exe, then you can see the services we started in the list of services:
The command to uninstall the service is: installutil/u ConsoleApplication.exe
After we modify the code, we need to unload the service before we can rebuild the success
③ Start Service
After starting the service, wait a moment to stop the service, then we open the 1.txt document under D, and we can see the results shown:
Second, commissioning
In the state of the service running, we find the menu bar, debug-attach to Process
Note Check the "Show All Users process" option, find our process, click Attach, and then add a breakpoint in the program, you can debug the program!
. NET development Windows Services summary