.NET控制台应用程序作为Windows服务 [英] .NET console application as Windows service

查看:148
本文介绍了.NET控制台应用程序作为Windows服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的控制台应用程序,并想运行它作为Windows服务。 VS2010有项目模板,允许附加控制台项目和构建Windows服务。 我想不加分离的服务项目,如果可能的整合服务code到控制台应用程序,以保持控制台应用程序中的一个项目可能运行的话,例如使用交换机命令行控制台应用程序或Windows服务运行。

I have console application and would like to run it as Windows service. VS2010 has project template which allow to attach console project and build Windows service. I would like to not add separated service project and if possible integrate service code into console application to keep console application as one project which could run as console application or as windows service if run for example from command line using switches.

也许有人可以建议类库或code段可能快速,方便地转换C#控制台应用程序服务?

Maybe someone could suggest class library or code snippet which could quickly and easily transform c# console application to service?

推荐答案

我通常使用以下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.

这篇关于.NET控制台应用程序作为Windows服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆