可靠地检测了我的另一个应用程序正在运行我的、应用程序、正在运行、可靠

2023-09-03 00:42:49 作者:記忆゛始終諟过去╮

我有两个应用程序,WinForms应用程序和Windows服务都将运行在同一台机器上。我想WinForms应用程序的服务运行时可靠地检测。我有完全的控制权这两个应用程序的设计和实现。

I have two applications, a WinForms app and a Windows Service that will both run on the same machine. I want the WinForms app to reliably detect when the service is running. I have complete control over the design and implementation of both applications.

我首先想到的是使用互斥,实例化的服务,并通过检测的WinForms应用程序。

My first thought is to use a Mutex, instantiated by the Service and detectable by the WinForms App.

有没有更好的设计?

推荐答案

互斥的路要走。这是一个很多比使用进程名等不那么脆弱。

Mutex is the way to go. It's a lot less fragile than using process names etc.

不过,你需要确保互斥是不是垃圾收集。在服务的情况下(这是事件驱动的,而不是它运行到完成主的方法),这样做的最明智的办法可能是把它放在一个静态变量。

However, you need to make sure the Mutex isn't garbage collected. In the case of a service (which is event driven rather than having a "main" method which runs to completion), the most sensible way of doing this is probably to put it in a static variable.

处置互斥的,当服务停止,所以你不必等待最后定稿之类的东西。

Dispose of the mutex when the service stops, so you don't need to wait for finalization or anything like that.