繁体   English   中英

如何运行在服务而不是后台进程下运行的 c# windows 服务应用程序?

[英]How to run c# windows service application run under services rather than background processes?

我有一个 Windows 服务应用程序,我在 Visual Studio 中用 c# 构建。 基本上,该应用程序从 API 服务中获取数据并使用 SDK 保存到我机器上安装的另一个软件中。 该应用程序运行良好,但它在 Windows 的后台进程下运行。 但我希望它在服务中运行

在此处输入图片说明

这是我的 program.cs main() 代码

static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    static void Main()
    {
        Service1 myService = new Service1();
        myService.OnDebug();
        System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);
    }

    
}

我可以在这里更改以在 Windows 服务下运行它吗?

您需要在您的服务中注册您的 .exe。

你可以在你的powershell中运行这一行:

New-Service -Name "YourServiceName" -BinaryPathName <yourproject>.exe

有关更多详细信息: https : //docs.microsoft.com/en-us/dotnet/framework/windows-services/how-to-install-and-uninstall-services

简短回答:使用“Windows 服务”模板重新创建您的项目,如下所述:

https://docs.microsoft.com/en-us/dotnet/framework/windows-services/walkthrough-creating-a-windows-service-application-in-the-component-designer

然后使用 installutil 或使用集成安装程序安装它

更长的答案:

服务是具有特定入口点的“控制台应用程序”,因此这是创建服务的非常基本的代码:

using System.ServiceProcess;

namespace WindowsService1
{
    public partial class Service1 : ServiceBase
    {
        public Service1()
        {
            this.ServiceName = "Service1";
        }

        protected override void OnStart(string[] args)
        {
        }

        protected override void OnStop()
        {
        }
    }
}

如您所见,主类继承并实现了“ServiceBase”类并覆盖了一些方法。 主要方法是“OnStart”(在启动服务时调用)和“OnStop”(在停止服务时调用)。

还有很多其他属性和方法,这里描述(或在visual studio中按F12在类名上):

https://docs.microsoft.com/en-us/dotnet/api/system.serviceprocess.servicebase

看看“主要”,你可以看到它是如何工作的:

    static void Main()
    {
        ServiceBase[] ServicesToRun;
        ServicesToRun = new ServiceBase[]
        {
            new Service1()
        };
        ServiceBase.Run(ServicesToRun);
    }

你必须记住的几件事:

  • 服务在 c:\\windows\\system32 中作为基本路径执行。 不要使用相对路径。

  • OnStart 必须很快。 不要在该方法中执行长时间的操作。 最好的做法是执行所有启动检查并启动一个线程。

  • 以这种方式更改 main 以允许调试(显然 TestMode 应该是要测试的代码):

    bool isInteractive = Environment.UserInteractive || args.Contains("--interactive");

    if (isInteractive) ((Service1)ServicesToRun[0]).TestMode(); 否则 ServiceBase.Run(ServicesToRun);

  • 构建 .exe 文件后,使用 installutil 将其安装为服务

    使用 Windows 命令提示符安装 Windows 服务?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM