如何与Windows服务进行通信?

Ale*_*psa 32 c# windows-services ipc

我想创建一个Windows服务,验证数据并从另一个Windows应用程序访问它,但我是新的服务,我不知道如何开始.

因此,在服务运行时,Windows应用程序应以某种方式连接到服务,发送一些数据并获得响应,无论是真还是假.

小智 34

我可以成功地处理(几乎)与您执行以下操作相同的问题:

在您的Class:ServiceBase中,代表您的Service类,您可能具有:

public Class () //constructor, to create your log repository
    {
      InitializeComponent();

      if (!System.Diagnostics.EventLog.SourceExists("YOURSource"))
      {
        System.Diagnostics.EventLog.CreateEventSource(
           "YOURSource", "YOURLog");
      }
      eventLog1.Source = "YOURSource";
      eventLog1.Log = "YOURLog";
    }
Run Code Online (Sandbox Code Playgroud)

现在,实施:

protected override void OnStart(string[] args)
{...}
Run Code Online (Sandbox Code Playgroud)

protected override void OnStop()
{...}
Run Code Online (Sandbox Code Playgroud)

要处理自定义命令调用:

protected override void OnCustomCommand(int command)
    {
      switch (command)
      {
        case 128:
          eventLog1.WriteEntry("Command " + command + " successfully called.");
          break;
        default:
          break;
      }
    }
Run Code Online (Sandbox Code Playgroud)

现在,在您将调用Windows服务的应用程序中使用它:

枚举引用您的方法:(请记住,服务自定义方法总是接收int32(128到255)作为参数并使用Enum使您更容易记住和控制您的方法

private enum YourMethods
  {
    methodX = 128
  };
Run Code Online (Sandbox Code Playgroud)

要调用特定方法:

ServiceController sc = new ServiceController("YOURServiceName", Environment.MachineName);
ServiceControllerPermission scp = new ServiceControllerPermission(ServiceControllerPermissionAccess.Control, Environment.MachineName, "YOURServiceName");//this will grant permission to access the Service
    scp.Assert();
    sc.Refresh();

    sc.ExecuteCommand((int)YourMethods.methodX);
Run Code Online (Sandbox Code Playgroud)

这样做,您可以控制您的服务.

您可以在此处查看如何创建和安装Windows服务. 有关ExecuteCommand方法的更多信息.

祝好运!

  • 有没有办法可以向服务发送除 int 之外的其他内容(比如字符串)?我如何在我的应用程序中获得返回值(由服务发送) (2认同)

Rob*_*ine 5

如果您使用的是 .Net Framework 4,那么内存映射文件提供了一种实现跨进程通信的相当简单的方法。

它相当简单,并且在文档中得到了很好的描述,并且避免了使用 WCF 或其他基于连接/远程处理的交互或将共享数据写入中央位置和轮询(数据库、文件等)。

有关概述,请参见此处


poi*_*r12 3

您可以通过使该服务托管 WCF 服务并从您的应用程序连接到它来轻松完成此任务。

  • @Rob,您不必让服务侦听 TCP 端口。WCF 可以使用命名管道在同一台计算机上的应用程序之间进行通信。当然,如果桌面应用程序位于另一台计算机上,则您必须有一个开放端口,但我认为这种情况并非如此。 (2认同)