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

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

问题描述

我有控制台应用程序并希望将其作为 Windows 服务运行.VS2010 有项目模板,允许附加控制台项目和构建 Windows 服务.我不想添加单独的服务项目,如果可能的话,将服务代码集成到控制台应用程序中,以将控制台应用程序作为一个项目,如果使用开关从命令行运行,则该项目可以作为控制台应用程序或 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.

也许有人可以建议可以快速轻松地将 c# 控制台应用程序转换为服务的类库或代码片段?

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

推荐答案

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

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

using System.ServiceProcess

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 通常对于控制台应用程序为 true,对于服务为 false.从技术上讲,可以在用户交互模式下运行服务,因此您可以改为检查命令行开关.

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天全站免登陆