正文

用C#创建Windows Service 2006-06-02 09:34:00

【评论】 【打印】 【字体: 】 本文链接:http://blog.pfan.cn/Csharpsky/15320.html

分享到:

Blog统计

  • 原创 - 48
  • 翻译 - 0
  • 转贴 - 1
  • 点击 - 12398
  • 评论 - 60
  • Trackbacks -4

公告

原来自己可以更努力一点 knight94cn@etang.com

文章

收藏

    相册

      网址推荐

      存档

      最近评论

       如何用C#创建Windows Service

      .Net中用C#创建Windows Service,其实很简单,按照以下的步骤就可以做出一个简单的Windows Service

      1.首先在创建工程的时候选择Windows Service,这样.Net会自动生成Windows Service的框架;

      2.完成Windows Service的相应事件,主要是OnStartOnStop这两个事件,完成后大致代码如下:

      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

                  {

                      Process.Start("net","send localhost yourValue");

                      try

                      {

                          myWriter=new StreamWriter("c:\\MyLog.txt",true);

                          myWriter.WriteLine(DateTime.Now.ToString());

                          myWriter.Close();

                      }

                      catch{};

       

                      Thread.Sleep(5000);

                  }while(blnStopThread==false);

                 

              }

          }

      }

             注:为了使自己能更好的识别自己写的Windows Service,建议在InitializeComponent修改Service的名称。

       

      3.为了使自己写的Service能加载到系统中去,光靠以上步骤是不够;接下来,向当前的工程添加Service Installer,在其中设置Service安装后的起始状态,代码如下:

      using System;

      using System.Collections;

      using System.ComponentModel;

      using System.Configuration.Install;

      using System.ServiceProcess;

       

       

      namespace WinSDemo

      {

          /// <summary>

          /// Summary description for WinSDemoIns.

          /// </summary>

          [RunInstaller(true)]

          public class WinSDemoIns : System.Configuration.Install.Installer

          {

              /// <summary>

              /// Required designer variable.

              /// </summary>

              private System.ComponentModel.Container components = null;

              private ServiceInstaller serviceInstaller;

              private ServiceProcessInstaller processInstaller;

       

              public WinSDemoIns()

              {

                  // This call is required by the Designer.

                  InitializeComponent();

       

                  // TODO: Add any initialization after the InitComponent call

                  processInstaller = new ServiceProcessInstaller();

                  serviceInstaller = new ServiceInstaller();

       

                  // Service will run under system account

                  processInstaller.Account = ServiceAccount.LocalSystem;

       

                  // Service will have Start Type of Manual

                  serviceInstaller.StartType = ServiceStartMode.Automatic;

       

                  serviceInstaller.ServiceName = "MyTest";

       

                  Installers.Add(serviceInstaller);

                  Installers.Add(processInstaller);

              }

       

              #region Component Designer generated code

              /// <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();

              }

              #endregion

          }

      }

       

      4.完成以上的步骤,代码的部分就完成了,编译成可执行文件,再用.NetService安装工具就行了,即在Dos窗口中,键入“installutil yourService.exe”,这样执行就可以了,相反,如果想卸载Service的话,加一个参数就可以了,即“installutil /u yourService.exe”。注意有可能.Net的路径在环境变量中不存在,可能直接执行是不能成功的,希望先找到“installutil.exe”存在的目录,大致在“\WINDOWS\Microsoft.NET\Framework\v1.1.4322”目录下。

       

      至于以后Service的部署,由于.Net写的程序,运行环境必须要安装.Net Framework,所以在其他机器安装自己写的Service时候,一定要先安装.Net运行环境。

       

      阅读(3575) | 评论(0)


      版权声明:编程爱好者网站为此博客服务提供商,如本文牵涉到版权问题,编程爱好者网站不承担相关责任,如有版权问题请直接与本文作者联系解决。谢谢!

      评论

      暂无评论
      您需要登录后才能评论,请 登录 或者 注册