write
Window
Service
First, Intuitively understand the Windows service.
Open Windows Control Panel / Administrative Tools / Services, the system displays a list of Windows services.
Double-click the service, you can display and change the service properties. In this dialog, you can control the boot, pause, and stop of the service. Here you can also configure the service start type, which makes the service boot when the system is started. Therefore, Windows services are often run as a server program.
In the fault restore this property page, you can configure the corresponding system's failure system. Some virus programs are articles here and activate the virus program.
Second, the development point of Windows service
In the random document of Visual Studio, the development steps of the Windows service program are introduced in detail, and the author is not described again. Readers just pay attention to a few points:
1. Create a derived entry class from ServiceBase. This entry class manages the survival of this Windows service.
Public class myService: system.serviceProcess.serviceBase
{
......
}
2. Register the service to the Windows service controller (SCM) of the WINDOWS service controller (SCM):
......
System.ServiceProcess.serviceBase [] ServicesTorun;
ServicesTorun = new system.serviceProcess.serviceBase [] {new myservice ()};
System.ServiceProcess.serviceBase.Run (ServiceStorun);
......
3, rewrite
Onstart,
ONSTOP, or
Onpause and
The onContinue method responds to the changes of the service status. Need usually need to rewrite
OnStart method, the resource is released in the onStop method when the service is ended, and it is rewritten as appropriate.
Onpause and
ONCONTINUE method.
4. Windows services typically start a timer to schedule or poll for business processing.
5, Windows services need to be used after installation. Windows services are usually installed in two ways:
Run InstallUtil.exe in the command line; add an instance of the ProjectInstraller class in the code of the Windows service, which contains an instance of the ServiceProcessInstaller class and a ServiceInstaller class.
The above two methods are described in the random document of Framework, and will not be described here.
6, Windows Services run in Windows's service controller (SCM), so debugging is not as simple as other Visual Studio applications. Regarding the debugging of Windows services, there is a presentation in the random document of Visual Studio, and details are not described here.
Third, the exception handling of Windows services
The Windows service does not have a user interface, which is difficult to notify the user during the run. Typically, the Windows service has an exception that occurs during the run, which may cause the service to run, but there is no reminder.
A recommended approach is to capture exceptions in a Windows service and write exception information in the Windows event log. Open Windows "Control Panel / Management Tools / Event Viewer", the system displays the Windows event log.
In an actual application, the author adds a serious error to the relevant personnel in addition to the event log in the event log. At the same time, all information recorded in the event log is redirected to a self-developed console program to monitor the service at any time. Third, the development points and techniques of Windows event logs
In the random document of Visual Studio, in the development steps of the Windows service, how to join the event log to the Windows service, and the author will not repeat it. The main points of development are as follows:
1. Create an instance EventLog of EventLog in a class that needs to be written to log, add the code in the constructor:
IF (! system.diagnostics.eventlog.sourceexists ("mysource")))
{
System.Diagnostics.eventlog.createEventSource ("MySource", "MyEventLog");
}
EventLog.source = "mysource";
EventLog.log = "myeventlog";
2. Write a log in the place where you need to write an event log, for example:
protected override void onstop ()
{
EventLog.WriteEntry ("in onstop.");
}
Readers can try to use the following skills in practical applications.
1. Package the code written to the Windows event log into a separate class, not only in the Windows service, but also use the Windows event log in other service code. See an attachment.
2, for convenient debugging and tracking, Visual SDudio provides Trace class. In the application's debug compiling, you can write debugging and tracking information to the console with the Trace class. There is a trick that you can write the contents of the write TRACE to the Windows event log. The points are as follows:
First, declare an instance of an event monitors EventLogTraceListener,
Static Private EventLogTraceListener CTracelistener = New EventLogTraceListener (m_eventlog);
Add an instance of EventLogTraceListener to Trace listening list:
Trace.LisTeners.Add (CTracelistener);
Thereafter, all debugging information written to Trace is written to the Windows event log. If you don't want to continue writing TRACE to the event log, run the following code:
Trace.Listeners.Remove (CTracelistener);
3. Write information on the event log, you can also write the display control in other application forms at the same time.
First open the design view of the form, select EventLog from the toolbox / component and join the form, configure the EventLog's EnableRaisingevents property to true.
Add EventLog's ENTRITTEN event processing method, the second parameter class behavior system.diagnostics.EntryWritteneventArgs, which contains the necessary content in the Windows event log entry, displaying the content in a display control in the form. can. The sample code is as follows:
///
/// Listen to the event log
/// summary>
/// param>
/// param> private void eventlog_entrywritten (Object Sender,
System.Diagnostics.EnTrywritteneventArgs E)
{
Try
{
// Write the log content to the list control named LISTEVENTLOG
Listeventlog.Items.insert (0,
E.Entry.TimeWritten ""
e.Entry.Message);
// List control Saves not more than 500 logs
While (Listeventlog.Items.count> 500)
{
Listeventlog.Items.removeat (Listeventlog.Items.count-1);
}
}
Catch (Exception EX)
{
Messagebox.show (ex.Message);
}
}
Fourth, communication with Windows service
In applications or other services, you can communicate with Windows services, including:
Manage the life of the Windows service, that is, open, stop, suspend, and restart services; get the properties and status of the Windows service; get a list of services on a specific computer; send commands to a specific service.
These operations are done through the ServiceController class. ServiceController is a visual control that can be found in the toolbox.
More interesting is the method of ExecuteCommand in ServiceController, calling this method, you can send a command to the Windows service to direct some of the operations of the Windows service. For example, there is a way to reply oncustomCommand () in the entry class of the Windows service:
///
// / Perform a user-defined message
/// summary>
/// message number param>
Protected Override Void OncustomCommand (Int Command)
{
Try
{
Switch (Command)
{
Case 1: // Business operation
DOBUSINESS1 ();
Break;
Case 2: // Business operation
DOBUSINESS2 ();
Break;
DEFAULT:
......
Break;
}
}
Catch (Exception EX)
{
// Error message
String strerrormsg = string.format ("exception: {0} / n", ex.Message);
// Write log
TLINEEVENTLOG.DOWRITEEVENTLOG (STRERRORMSG, EventTYPE.Error);
/ / Send an email to the administrator
Cmail.sendmail
PropertyManager.StrMailFromaddress, PropertyManager.StrmailadminaDial, "",
"Abnormal Information Tips",
STRERRORMSG);
// Write TRACE
Trace.writeline (strerrormsg);
}
}
Send commands to this Windows service in another application's ExecuteCumeCommand () method:
MyController.executeCommand (2); Windows service will execute business methods: dobusiness2 ();
It should be acknowledged that the features that use ServiceController and Windows service communications are currently very weak. You can only make simple and limited communication with the Windows service via ExecuteCommand.
In actual applications, the author uses a command line program, a console program, and a WebService and Windows service, start, stop the service, or the behavior of the ExecuteCommand control service.
Attachment: General class for manipulating Windows event logs
Using system;
Using system.diagnostics;
Using system.configuration;
Namespace mycommon.eventlog
{
Public enum evenettype {error, information, warning}
///
///
/// summary>
Public Class Tlineeventlog
{
// Task Log
Static private eventlog m_eventlog = new eventlog ();
// Source Name, read from the configuration file
Static private String M_StreventSource =
ConfigurationSettings.appsettings ["f_eventlog.source"]. TOSTRING (). TRIM ();
// Log name, read from the configuration file
Static private string m_streventlog =
ConfigurationSettings.AppSettings ["f_eventlog.log"]. TOSTRING (). Trim ();
// Debugging information Write log
Static Private EventLogTraceListener CTracelistener =
New EventLogtracelistener (m_eventlog);
// Default constructor. When the configuration file reads fails, provide the default source name and log name.
Public TLINEEVENTLOG ()
{
IF (M_StreventSource.length == 0)
M_StreventSource = "mysource";
IF (m_streventlog.length == 0)
m_streventlog = "mylog";
M_EventLog.Source = m_streventsource;
m_eventlog.log = m_streventlog;
}
// Constructor. Provide source names and log names.
Public TLINEEVENTLOG (String StreventSource, String Streventlog)
{
m_streventsource = streventsource;
m_streventlog = streventlog;
M_EventLog.Source = m_streventsource;
m_eventlog.log = m_streventlog;
}
///
/// write an event log
/// summary>
/// Event content param>
/// Event category, error, warning, or message param> static public void DowriteEventLog (String StrMessage, EventType Eventtype)
{
IF (! system.diagnostics.eventlog.sourceexists (m_streventsource))
{
System.Diagnostics.eventlog.createeventsource (
m_streventsource, m_streventlog);
}
EventLoGENTRYTYPE ENTRYTYPE = New EventLoGENTRYTYPE ();
Switch (evening "
{
Case evenettype. error:
ENTRYTYPE = EVENTLOGENTRYTYPE.ERROR;
Break;
Case evenettype.information:
EntryType = EventLoGentrytype.information;
Break;
Case eventtype.warning:
ENTRYTYPE = EVENTLOGENTRYTYPE.WARNING;
Break;
DEFAULT:
EntryType = EventLoGentrytype.information;
Break;
}
M_EventLog.WriteEntry (StrMessage, Entrytype);
}
///
/// write an event log, default is a message
/// summary>
/// Event content param>
Static Public Void DowriteEventLog (String StrMessage)
{
IF (! system.diagnostics.eventlog.sourceexists (m_streventsource))
{
System.Diagnostics.eventlog.createeventsource (
m_streventsource, m_streventlog);
}
m_eventlog.writeentry (StrMessage);
}
///
/// Debugging information writes log
/// summary>
Public static void OpenTRACE ()
{
IF (ctracelistener! = null)
{
IF (! trace.listeners.contains (ctracelistener))
{
Trace.LisTeners.Add (CTracelistener);
}
}
}
///
/// Debug information does not write log
/// summary>
Public static void closetrace ()
{
IF (trace.listener.indexof (ctracelistener)> = 0)
{
Trace.Listeners.Remove (CTracelistener);
}
}
}
}
About the author: Zhang Wei, Lenovi Liitai Software Co., Ltd. (formerly Lenovo Software Design Center) E-Zhangyu@vip.sina.com