Simon Temlett
Simon Temlett

Reputation: 2487

.NET Check if another application is running

I have an application that provides core services for a series of other applications.

When another of these applications is started, I want to check that the service application is running and if not shutdown.

What is the best method to check for the existence of the other app? I'm thinking that I should be using a global mutex in the services app and checking for it's existence in the other apps. Is this the correct way to proceed?

Upvotes: 0

Views: 8552

Answers (5)

DB Pros
DB Pros

Reputation: 31

try the following (VB.NET example):

        If PrevInstance() Then
            MsgBox("[MyApplicationName] application is already running.")
            Exit Sub
        End If


Function PrevInstance() As Boolean
    If UBound(Diagnostics.Process.GetProcessesByName(Diagnostics.Process.GetCurrentProcess.ProcessName)) > 0 Then
        'MsgBox("Application is still running", MsgBoxStyle.Information)
        Return True
    Else
        Return False
    End If
End Function

Upvotes: 0

Paul Sonier
Paul Sonier

Reputation: 39480

I'd say to look into the method you're using for communication with the service app, and look at what the communication failure behaviour is. If you attempt to communicate with the service app at any time and fail, it looks like you want to have failure behaviour, because of the high dependency. If you have a failure at first communication, it seems like you want to exit the application; but you also have to worry about what happens if your communication fails at some later point, too.

Upvotes: 0

RichardOD
RichardOD

Reputation: 29157

Yes- just be careful what you call the mutex. There are specific naming guidelines for these- this has some details

Upvotes: 0

NinethSense
NinethSense

Reputation: 9028

bool IsApplicationAlreadyRunning()
{
string proc=Process.GetCurrentProcess().ProcessName;
Process[] processes=Process.GetProcessesByName(proc);
if (processes.Length > 1)
return true;
else
return false;
}

Source: http://kseesharp.blogspot.com/2008/11/c-check-if-application-is-already.html

Upvotes: 4

Martin Peck
Martin Peck

Reputation: 11544

The global mutex approach is a good one, and one that many apps use.

For example, Windows Media Player does this.

Related question:

Is using a Mutex to prevent multiple instances of the same program from running safe?

Upvotes: 3

Related Questions