Create a combo command line / Windows service app

前端 未结 4 602
说谎
说谎 2021-02-02 16:19

What\'s the best way in C# to set up a utility app that can be run from the command line and produce some output (or write to a file), but that could be run as a Windows service

4条回答
  •  一生所求
    2021-02-02 17:07

    Yes you can.

    One way to do it would be to use a command line param, say "/console", to tell the console version apart from the run as a service version:

    • create a Windows Console App and then
    • in the Program.cs, more precisely in the Main function you can test for the presence of the "/console" param
    • if the "/console" is there, start the program normally
    • if the param is not there, invoke your Service class from a 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();
        }
    }
    

    ...

    Then in 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);
        }
    }
    

    }

提交回复
热议问题