代码之家  ›  专栏  ›  技术社区  ›  marc_s MisterSmith

创建组合命令行/Windows服务应用程序

  •  11
  • marc_s MisterSmith  · 技术社区  · 16 年前

    在C中,设置一个可以从命令行运行并产生一些输出(或写入文件)的实用程序的最佳方法是什么,但是它可以作为Windows服务运行,也可以在后台执行它的工作(例如监视目录或其他)。

    我想写一次代码,并能够从PowerShell或其他一些CLI以交互方式调用它,但同时也找到一种方法,将同一个exe文件安装为Windows服务,并让它以无人值守的方式运行。

    我可以这样做吗?如果是的话:我该怎么做?

    4 回复  |  直到 16 年前
        1
  •  18
  •   JustBeingHelpful    10 年前

    是的,你可以。

    一种方法是使用命令行参数,例如“/console”,将控制台版本与作为服务运行的版本区分开来:

    • 创建Windows控制台应用程序,然后
    • 在program.cs中,更准确地说,在主函数中,您可以测试“/console”参数是否存在。
    • 如果有“/console”,则正常启动程序
    • 如果参数不存在,请从ServiceBase调用服务类

    
    // Class that represents the Service version of your app
    public class serviceSample : ServiceBase
    {
        protected override void OnStart(string[] args)
        {
            // Run the service version here 
            //  NOTE: If you're task is long running as is with most 
            //  services you should be invoking it on Worker Thread 
            //  !!! don't take too long in this function !!!
            base.OnStart(args);
        }
        protected override void OnStop()
        {
            // stop service code goes here
            base.OnStop();
        }
    }
    

    然后在program.cs中:

    
    static class Program
    {
        // The main entry point for the application.
        static void Main(string[] args)
        {
            ServiceBase[] ServicesToRun;
    
    
        if ((args.Length > 0) && (args[0] == "/console"))
        {
            // Run the console version here
        }
        else
        {
            ServicesToRun = new ServiceBase[] { new serviceSample () };
            ServiceBase.Run(ServicesToRun);
        }
    }
    

    }

        2
  •  4
  •   juhan_h    16 年前

    从设计的角度来看,实现这一点的最佳方法是在库项目中实现所有功能,并围绕库项目构建单独的包装器项目,以执行所需的方式(即Windows服务、命令行程序、ASP.NET Web服务、WCF服务等)。

        3
  •  3
  •   marc_s MisterSmith    16 年前

    是的,可以做到。

    启动类必须扩展ServiceBase。

    可以使用静态void main(string[]args)启动方法来分析命令行开关以在控制台模式下运行。

    类似:

    static void Main(string[] args)
    {
       if ( args == "blah") 
       {
          MyService();
       } 
       else 
       {
          System.ServiceProcess.ServiceBase[] ServicesToRun;
          ServicesToRun = new System.ServiceProcess.ServiceBase[] { new MyService() };
          System.ServiceProcess.ServiceBase.Run(ServicesToRun);
       }
    
        4
  •  1
  •   Community Mohan Dere    8 年前

    Windows服务与普通的Windows程序有很大的不同;最好不要同时做两件事。

    你考虑过把它改成计划任务吗?

    windows service vs scheduled task