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

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

问题描述

如以下链接所示,可以使用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/

我烘焙了一个.NET服务,该服务确实实现了 OnStart OnStop 。但是,我需要实现智能重启功能,而不仅仅是停止然后再启动。如果那样的话,我需要将停机时间保持在几秒钟之内(但在干净的情况下,停止+启动在这种情况下可能需要几分钟的时间,因此我必须干净地进行),并使系统的某些部分可用,而其他部分则需要重新引导/刷新

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

You can send "commands" to a service using 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 Service发送自定义命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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