Converting a c# commandline app to a Windows service

后端 未结 3 534
逝去的感伤
逝去的感伤 2021-01-01 04:45

I found plenty of partial answers, but nothing really sufficient.

The case: App is a working command line app, with no user interaction, except for the ability to re

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-01 05:27

    Keep C# application running

    public partial class DemoService : ServiceBase
    {
        static void Main(string[] args)
        {
            DemoService service = new DemoService();
    
            if (Environment.UserInteractive)
            {
                service.OnStart(args);
                Console.WriteLine("Press any key to stop program");
                Console.Read();
                service.OnStop();
            }
            else
            {
                ServiceBase.Run(service);
            }
        }
    

    Check the link above. I provide some code as well as a link describing using a console for double-duty as Console and Service. I will use a console project and check for UserInteractive before running as a service. This way you can debug as if it's a console, but install it as a service on a production server.

    With regards to installing, I don't have experience with installing from .msi, but we use a batch script to install the service (using sc.exe) and then its just a matter of replacing files if you update the code.

提交回复
热议问题