using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
namespace LogWriterService
{
public class Service1 : System.ServiceProcess.ServiceBase
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
public Service1()
{
// The Windows.Forms Component Designer must have this call.
InitializeComponent();
// TODO: Add any initialization after the InitComponent call
}
// The main entry point for the process
static void Main()
{
System.ServiceProcess.ServiceBase[] ServicesToRun;
// More than one user service may run in the same process. To add
// another service to this process, change the following line to
// create a second service object. For example,
//
// ServicesToRun = New System.ServiceProcess.ServiceBase[] {new Service1(), new MySecondUserService()};
//
ServicesToRun = new System.ServiceProcess.ServiceBase[] { new Service1() };
System.ServiceProcess.ServiceBase.Run(ServicesToRun);
}
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
components = new System.ComponentModel.Container();
this.ServiceName = "Service1";
}
/// <summary>
/// Clean up any resources that are being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
/// <summary>
/// Set things in motion so your service can do its work.
/// </summary>
protected override void OnStart(string[] args)
{
EventLog.WriteEntry("My simple service started.");
}
/// <summary>
/// Stop this service.
/// </summary>
protected override void OnStop()
{
// TODO: Add code here to perform any tear-down necessary to stop your service.
}
}
}
验证它工作
1.
在控制面板, 双击 管理工具 , 然后双击 服务
2.
右击 Service 1 , 并单击 开始
3.
使用下列方法之一来验证该事件日志中记录的事件:
•
方法 1
a.
在控制面板, 双击 管理工具 , 并双击 事件查看器 。
b.
在左窗格中, 单击 Application 日志 , 然后定位事件日志用于您服务从右窗格中。
•
方法 2
a.
在 ServerExplorer@@, 展开 服务器 、 ComputerName 展开 Application ,、 事件日志 和展开 Service 1 。 记住, Service 1 是类, 不服务本身的名称。 因此, Service 1 用作应用程序名称。 (它是超出了本文将解释如何自定义名称范围。