I understand how to use Mutex to limit an application to run only a single instance at one time. However, in my application I allow multiple instances to run simultaneously, but I need a way to count and/or list all of the running instances for a given user, regardless of whether or not the executable file has been renamed. Can Mutex be used here or is the process class able to do this? I know how to use the process class to list processes by name, but what if the exe has been renamed by the user? How is this best handled?
EDIT: For my purposes it turned out to be sufficient to merely be able to count other instances of the same application rather than list them out. To count them I used a named semaphore.
//Initialize the semaphore with an initial value of 10000 and a maximum value of 10000. The 'Global\' prefix will be system wide. Remove it to limit the semaphore to the current logon session
Semaphore mySemaphore = new Semaphore(10000, 10000, @"Global\mySemaphoreUniqueNameGoesHere");
//Call .WaitOne() to enter the semaphore and decrement the semaphore count
mySemaphore.WaitOne();
Since each running instance of the application will decrement the count by 1, then any time I need to check how many instances of the application are running I can use:
//.Release() will exit the semaphore and increment the semaphore count, but it will also return the value of the count just before .Release() was called, which is what we really need here.
int numberOfRunningInstances = 10000 - mySemaphore.Release();
//Then we can simply use .WaitOne() to re-enter the semaphore and decrement the count back to what it was before calling .Release()
mySemaphore.WaitOne();
Then when the application exits:
//call .Release() to exit the semaphore and increment the count
mySemaphore.Release()