且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

.NET控制台应用程序作为Windows服务

更新时间:2022-03-14 23:03:52

我通常使用以下techinque运行相同的应用程序作为控制台应用程序或服务:

I usually use the following techinque to run the same app as a console application or as a service:

public static class Program
{
    #region Nested classes to support running as service
    public const string ServiceName = "MyService";

    public class Service : ServiceBase
    {
        public Service()
        {
            ServiceName = Program.ServiceName;
        }

        protected override void OnStart(string[] args)
        {
            Program.Start(args);
        }

        protected override void OnStop()
        {
            Program.Stop();
        }
    }
    #endregion

    static void Main(string[] args)
    {
        if (!Environment.UserInteractive)
            // running as service
            using (var service = new Service())
                ServiceBase.Run(service);
        else
        {
            // running as console app
            Start(args);

            Console.WriteLine("Press any key to stop...");
            Console.ReadKey(true);

            Stop();
        }
    }

    private static void Start(string[] args)
    {
        // onstart code here
    }

    private static void Stop()
    {
        // onstop code here
    }
}

Environment.UserInteractive 是控制台应用程序通常真假的服务。 Techically,就可以在用户交互模式下运行的服务,让您可以检查命令行开关来代替。

Environment.UserInteractive is normally true for console app and false for a service. Techically, it is possible to run a service in user-interactive mode, so you could check a command-line switch instead.