Reliable detection of another application

I have two applications: a WinForms application and a Windows service that will run on the same computer. I want the WinForms application to reliably detect when the service is running. I have full control over the design and implementation of both applications.

My first thought is to use the Mutex created by the service and detected by the WinForms application.

Is there a better design?

0
source share
6 answers

Mutex is the way to go. It is much less fragile than process names, etc.

However, you need to make sure that Mutex is not a garbage collection. In the case of a service (which is event driven, and does not have a “main” method that ends), the most sensible way to do this is probably to put it in a static variable.

Dispose of the mutexes when the service stops, so you don’t need to wait for completion or something like that.

+3
source

C. Scott Allen is a good entry on using Mutex for this purpose and the problems you will encounter with GC.

If I want to have only one instance of the application running in all sessions on the computer, I can put the named mutex in the global namespace with the prefix "Global".

[STAThread] static void Main() { using(Mutex mutex = new Mutex(false, "Global\\" + appGuid)) { if(!mutex.WaitOne(0, false)) { MessageBox.Show("Instance already running"); return; } Application.Run(new Form1()); } } 

EDIT: Modified string literal to use hidden backslash instead of @ , SO syntax syntax did not like verbatim.

+7
source

You can use Mutex, but instead you can use the ServiceController class. This will let you know if the service is installed, and if it is not already running, start it if applicable.

http://msdn.microsoft.com/en-us/library/system.serviceprocess.servicecontroller_members.aspx

+2
source

You can implement some “Connection Test Function” in the service. I don't know if this will work for your requirements. When you start winforms, you can call the service to find out if it is alive. You can open the service using a simple WCF contract.

Hope this helps ...

+1
source

similar question [according to the answers there, you are on the right track]

0
source

Alternatively, your WinForms application can check the list of running services to see if the service is running.

0
source

All Articles