In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
Today, the editor will share with you the relevant knowledge points about how to create and control Windows services in C#. The content is detailed and the logic is clear. I believe most people still know too much about this knowledge, so share this article for your reference. I hope you can get something after reading this article.
Demand
For a special application, do not need to display GUI, want to resident in the Windows service, when necessary, we can start or boot.
At this point, we can create a WindowsService to implement.
Create WindowsService
The following demonstrates the use of VisualStudio2019 to create a Windows service based on the .net Framework
The project structure is as follows:
Contains a startup item and a service class
Right-click on the Service1 code, as shown below, including overriding the OnStart method and the OnStop method:
Public partial class Service1: ServiceBase {public Service1 () {InitializeComponent ();} protected override void OnStart (string [] args) {} protected override void OnStop () {}}
When the service is started, it starts the code executed within the OnStart method, while in ServiceBase, many types of methods are also provided to be rewritten.
When we have finished writing the execution code for the service, the next step is to add an installer to it.
Double-click Service1.cs, and then right-click to add the installer, as follows:
At this point, a new default name is added to the project structure: ProjectInstaller.cs class, and the corresponding design page is as follows:
ServiceProcessInstaller1:
View the properties of the class, as follows:
Description:
Account: the default setting is User, and when the Account property is User, Username, and Password properties are used to define the account used to run the service application.
Username and Password pairs allow the service to run under an account other than the system account. For example, if no user is logged in, you can allow the service to start automatically when it restarts. If you leave Username or Password blank and set Account to User, you will be prompted for a valid user name and password during installation.
You can also specify that the service runs under the local system account or as a local or network service. For more information about account types from ServiceAccount, see enumeration:
ServiceInstaller1:
View the properties of the class, as follows:
Note: this class extends ServiceBase to implement the service. This class is called by the installation utility when the service application is installed.
Description:
DelayedAutoStart: to delay the automatic start of the service, true; otherwise false. The default is false.
Description: description of the service. The default value is an empty string (").
DisplayName: the name associated with the service, often used in interactive tools.
ServiceName: the name of the service to install. This value must be set before the installation utility attempts to install the service.
ServicesDependedOn: a set of services that must be run before the services associated with this installer can run.
StartType: indicates how the service is started. The default value is Manual, which specifies that the service will not start automatically after the computer restarts.
Control WindowsService
After the service is created, the next step is to control the service, and now you can use the ServiceController class to connect and control the behavior of the existing service.
ServiceController: represents a Windows service and allows you to connect to, operate on, or get information about a service that is running or stopped.
Through ServiceController, we can obtain local Service services, as well as start, pause, renew, suspend, close, refresh and other actions, as shown below:
The following example shows how to use the ServiceController class to control the Service1 service example.
Using System;using System.ServiceProcess;using System.Diagnostics;using System.Threading;namespace ServiceControllerSample {class Program {public enum SimpleServiceCustomCommands {StopWorker, RestartWorker, CheckWorker}; static void Main (string [] args) {ServiceController [] scServices; scServices = ServiceController.GetServices () Foreach (ServiceController scTemp in scServices) {if (scTemp.ServiceName = = "Service1") {/ / Display properties for the Simple Service sample / / from the ServiceBase example. ServiceController sc = new ServiceController ("Simple Service"); Console.WriteLine ("Status =" + sc.Status); Console.WriteLine ("CanPause and Continue =" + sc.CanPauseAndContinue); Console.WriteLine ("Can ShutDown =" + sc.CanShutdown); Console.WriteLine ("CanStop =" + sc.CanStop) If (sc.Status = = ServiceControllerStatus.Stopped) {sc.Start (); while (sc.Status = = ServiceControllerStatus.Stopped) {Thread.Sleep (1000); sc.Refresh () }} / / Issue custom commands to the service / / enum SimpleServiceCustomCommands / / {StopWorker = 128, RestartWorker, CheckWorker}; sc.ExecuteCommand ((int) SimpleServiceCustomCommands.StopWorker); sc.ExecuteCommand ((int) SimpleServiceCustomCommands.RestartWorker) Sc.Pause (); while (sc.Status! = ServiceControllerStatus.Paused) {Thread.Sleep (1000); sc.Refresh ();} Console.WriteLine ("Status =" + sc.Status) Sc.Continue (); while (sc.Status = = ServiceControllerStatus.Paused) {Thread.Sleep (1000); sc.Refresh ();} Console.WriteLine ("Status =" + sc.Status) Sc.Stop (); while (sc.Status! = ServiceControllerStatus.Stopped) {Thread.Sleep (1000); sc.Refresh ();} Console.WriteLine ("Status =" + sc.Status) String [] argArray = new string [] {"ServiceController arg1", "ServiceController arg2"}; sc.Start (argArray); while (sc.Status = = ServiceControllerStatus.Stopped) {Thread.Sleep (1000); sc.Refresh () } Console.WriteLine ("Status =" + sc.Status); / / Display the event log entries for the custom commands / / and the start arguments. EventLog el = new EventLog ("Application"); EventLogEntryCollection elec = el.Entries Foreach (EventLogEntry ele in elec) {if (ele.Source.IndexOf ("Service1.OnCustomCommand") > = 0 | ele.Source.IndexOf ("Service1.Arguments") > = 0) Console.WriteLine (ele.Message) } / / This sample displays the following output if the Simple Service//sample is running://Status = Running//Can Pause and Continue = True//Can ShutDown = True//Can Stop = True//Can Stop = True//Status = Paused//Status = Running//Status = Stopped//Status = Running//4:14:49 PM-Custom command received: 128Greater 4GN 1415 49 PM-Custom command received: 129//ServiceController arg1//ServiceController arg2 installation WindowsService
The premise that we can control the service we create is that it is already installed on the device we are debugging, and we can install it through the AssemblyInstaller class.
Installation example
In the following example, AssemblyInstaller is created by calling the AssemblyInstaller constructor. Set the properties of this object and Install Commit calls and methods to install the MyAssembly.exe assembly.
Using System;using System.Configuration.Install;using System.Collections;using System.Collections.Specialized;class AssemblyInstaller_Example {static void Main () {IDictionary mySavedState = new Hashtable (); Console.WriteLine (""); try {/ / Set the commandline argument array for 'logfile'. String [] commandLineOptions = new string [1] {"/ LogFile=example.log"}; / / Create an object of the 'AssemblyInstaller' class. AssemblyInstaller myAssemblyInstaller = new AssemblyInstaller ("MyAssembly.exe", commandLineOptions); myAssemblyInstaller.UseNewContext = true; / / Install the 'MyAssembly' assembly. MyAssemblyInstaller.Install (mySavedState); / / Commit the 'MyAssembly' assembly. MyAssemblyInstaller.Commit (mySavedState);} catch (Exception e) {Console.WriteLine (e.Message);}} uninstall example
The following example shows the Uninstall method Installer. The Uninstall method is overridden Installer in a derived class of.
/ / Override 'Uninstall' method of Installer class.public override void Uninstall (IDictionary mySavedState) {if (mySavedState = = null) {Console.WriteLine ("Uninstallation Error!");} else {base.Uninstall (mySavedState); Console.WriteLine ("The Uninstall method of' MyInstallerSample' has been called");}} these are all the contents of the article "how to create and control Windows services in C#". Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.