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

标签 c# .net-4.0 windows-services console-application

我有控制台应用程序并想将其作为 Windows 服务运行。 VS2010 具有允许附加控制台项目和构建 Windows 服务的项目模板。 我不想添加单独的服务项目,如果可能的话,将服务代码集成到控制台应用程序中,以使控制台应用程序保持为一个项目,该项目可以作为控制台应用程序运行,或者如果使用开关从命令行运行,则作为 Windows 服务运行。

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

最佳答案

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

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

关于c# - .NET 控制台应用程序作为 Windows 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7764088/

相关文章:

c# - 在使用 .NET 4.0 的 x64 位机器上加载资源的静默失败背后的原因是什么?

c# - 使用 InstallUtil 安装带有启动参数的 Windows 服务

c# - Windows 服务 - 它可以运行两个以不同时间间隔安排的独立任务吗

c# - 路径绘制得太远

c# - 如何使用带有最大匹配量文档的剩余查询从Elastic搜索中获得前10个结果?

c# - 垂直进度条

c# - 创建辅助磁贴时出现操作无效错误

c# - Windows 7 任务栏中的跑马灯进度条

asp.net-mvc-3 - 为什么 WebGrid 在格式化时使用动态?

windows - 使用 FileSystemWatcher 在 Windows 服务中一次处理多个文件时出现问题