如何从 .NET 代码向 .NET Windows 服务发送自定义命令? [英] How to send a custom command to a .NET windows Service from .NET code?

查看:41
本文介绍了如何从 .NET 代码向 .NET Windows 服务发送自定义命令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如以下链接所示,您可以使用 C# 代码停止、启动和停止,然后启动"服务.

As in the following link, one can stop, start, and "stop, then start" a service using C# code.

http://www.csharp-examples.net/restart-windows-service/

我已经烘焙了一个实现 OnStartOnStop 的 .NET 服务.但是,我需要实现一个智能重启"功能,这不仅仅是停止然后启动.如果那样的话,我需要将停机时间保持在几秒钟(但是在这种情况下,如果干净地完成,停止 + 启动可能需要几分钟,我必须干净地完成),并且让系统的某些部分可用,而其他部分正在重新启动/刷新.

I have baked a .NET service that does implement OnStart and OnStop. However, I need to implement a "smart restart" functionality which is more involved than just stopping and then starting. I need to keep the downtime to just a few seconds if that (but Stop + Start can take minutes in this case when done cleanly, and I must do it cleanly), and having some parts of the system available while others are rebooting/refreshing.

长话短说 - 在我开始实现这个 OnSmartRestart 功能之前,我想确保有一种相当简单的方法可以从另一个 C# 应用程序调用这个调用.

Long story short - before I jump into implementing this OnSmartRestart functionality, I want to make sure that there is a fairly easy way to invoke this call from another C# application.

此功能很重要,但很危险.我想让它相当隐蔽,有点安全,也保持简单,并确保这对我的 Windows 服务在执行其常规杂务而不是重新启动时的性能影响可以忽略不计.

This feature is important, but dangerous. I want to make it fairly hidden, somewhat secure, also keep it simple, and make sure that this has negligible effect on the performance of my Windows service while it is performing its regular chores and not rebooting.

如果我必须轮询某个文件或打开一个端口并为此花费太多 CPU,这将不是一个好的解决方案.我也想让这个尽可能简单(抱歉重复).

If I have to poll for some file or open a port and spend too much CPU on doing that, it would not be a good solution. I also want to keep this AS SIMPLE AS POSSIBLE (sorry for repetition).

推荐答案

您可以使用 ServiceController.ExecuteCommand:

const int SmartRestart = 222;

var service = new System.ServiceProcess.ServiceController("MyService");
service.ExecuteCommand(SmartRestart);
service.WaitForStatus(ServiceControllerStatus.Running, timeout);

您需要添加对 System.ServiceProcess.dll 程序集的引用.

You'll need to add a Reference to the System.ServiceProcess.dll assembly.

服务可以通过覆盖 ServiceBase 对命令做出反应.OnCustomCommand:

protected override void OnCustomCommand(int command)
{
    if (command == SmartRestart)
    {
        // ...
    }
}

这篇关于如何从 .NET 代码向 .NET Windows 服务发送自定义命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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