与Windows服务的通讯

来源:互联网 发布:马布里cba比赛数据 编辑:程序博客网 时间:2024/04/29 21:43
       在应用程序或其他服务中,可以与Windows服务通讯,包括:
  •          管理Windows服务的生命期,即开启、停止、暂停和重启服务;
  •          获得Windows服务的属性和状态;
  •          获得特定计算机上的服务列表;
  •          向特定的服务发送命令。
        这些操作是通过ServiceController 类完成的。ServiceController是一个可视化控件,可以在工具箱中找到。
        比较有意思的是ServiceController 中ExecuteCommand这个方法,调用这个方法,可以向Windows服务发送命令,指挥Windows服务的一些操作。例如,在Windows服务的入口类中有一个复写OnCustomCommand()的方法:
         /// <summary>
         /// 执行用户自定义消息
         /// </summary>
         /// <param name="command">消息编号</param>
         protected override void OnCustomCommand( int command )
         {
              try
              {
                   switch( command )
                   {
                       case 1: // 业务操作
                            doBusiness1();
                            break;
                       case 2: //业务操作
                            doBusiness2();
                            break;
                       default:
                            ……
                            break;
                   }
              }
              catch( Exception ex )
              {
                   // 错误信息
                   string strErrorMsg = string.Format("异常:{0}/n", ex.Message );
                   // 写日志
                   TLineEventLog.DoWriteEventLog( strErrorMsg, EventType.Error );
                   // 给管理员发邮件
                   CMail.SendMail(
PropertyManager.strMailFromAddress, PropertyManager.strMailAdminAddress, "",
                       "异常信息提示",
strErrorMsg );
                   // 写Trace
                   Trace.WriteLine( strErrorMsg );
              }
         }
        在另外一个应用程序中通过ServiceController的ExecuteCommand()方法向这个Windows服务发送命令:
            myController.ExecuteCommand(2);
        Windows服务将执行业务方法:doBusiness2();
        应该承认,利用ServiceController与Windows服务通讯的功能目前还十分薄弱。通过ExecuteCommand只能与Windows服务进行简单而有限的通讯。
        笔者在实际的应用中,分别用一个命令行程序、一个控制台程序和一个Webservice和Windows服务进行通讯,启动、停止服务,或通过ExecuteCommand控制服务的行为。

http://blog.csdn.net/zhangyuk/article/details/338243

原创粉丝点击