如何用C#创建Windows Service
在.Net中用C#创建Windows Service,其实很简单,按照以下的步骤就可以做出一个简单的Windows Service。
1.首先在创建工程的时候选择Windows Service,这样.Net会自动生成Windows Service的框架;
2.完成Windows Service的相应事件,主要是OnStart和OnStop这两个事件,完成后大致代码如下:
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.IO;
using System.Threading;
namespace WinSDemo
{
public class WinSDemo : System.ServiceProcess.ServiceBase
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
private bool blnStopThread;
private Thread thdMain;
public WinSDemo()
{
// This call is required by the Windows.Forms Component Designer.
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 within 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 WinSDemo() };
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()
{
//
// WinSDemo
//
this.CanPauseAndContinue = true;
this.ServiceName = "MyTest";
}
/// <summary>
/// Clean up any resources 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)
{
// TODO: Add code here to start your service.
thdMain=new Thread(new ThreadStart(WriteLog));
thdMain.Start();
}
/// <summary>
/// Stop this service.
/// </summary>
protected override void OnStop()
{
// TODO: Add code here to perform any tear-down necessary to stop your service.
blnStopThread=true;
thdMain.Join();
}
protected override void OnPause()
{
thdMain.Suspend();
}
protected override void OnContinue()
{
thdMain.Resume();
}
protected void WriteLog()
{
StreamWriter myWriter=null;
do
 
补充:软件开发 , C# ,