Reputation: 25143
I want to insure mutual exclusion in my project for installing updates.
The project is multi-instance means one can open a instances without closing the other open instances. There is a function called installUpdates()
which installs the available updates. Since several instances are there so only one of them need to install the updates. I want to insure that only one instance will install the updates.
I am taking a variable globally called noOfInstances
(semaphore) initialized to 0
. Once a new instance is opened the variable will be incremented by 1. If there are 4 open instances then the value of noOfInstances
will be 4. Once a instance is closed the value will be decreased by 1. For installing the updates I am writing:-
if(noOfInstances == 1)
{
InstallUpdates();
}
Now my problem is that how to track programmatically that there is an instance opened of my project? There may be some unique Id for each instance which I am not able to identify. I am using windows environment to develop my c# application.
Upvotes: 1
Views: 2485
Reputation: 2163
You can get the Running Processes like this :
using System.Diagnostics;
int GetInstanceCount(ExeName)
{
Process[] processlist = Process.GetProcessesByName(ExeName);
int NoOfInstances = processlist.Count;
return NoOfInstances;
}
Now Implement Like This:
string ExeName = "notepad.exe"//Say Notepad
if(GetInstanceCount(ExeName) == 1)
{
InstallUpdates();
}
Upvotes: 0
Reputation: 56717
While I've implemented @stephbu's mutex-pattern in the past, requirements recently have been that the running instance should be brought to the front if the program was started twice.
To do so, I try to connect to a named pipe. If I can not connect, this is the first instance and I create the named pipe and then do things normally. If I can connect, this is a second instance and I send a command via the pipe and quit.
Receiving a command on the named pipe I can do anything I want, like bring the main window to the top.
This solution, however, only makes sense if you actually want to do something with the pipe as described above. If you only want to prevent the application from being run twice, @stephbu's mutex answer is the way to go.
Upvotes: 0
Reputation: 5092
A global Mutex is probably a better mechanism to gate access to exactly-once-only functions. In this instance I'd try acquire a mutex with a short timeout. If you fail to acquire it - someone else has it. If you succeed, test if updates are necessary, and if so install updates.
An optimization might be to move the test outside of the mutex - but you'll still need to retest if updates are required inside the scope of the mutex.
What is a good pattern for using a Global Mutex in C#?
Upvotes: 2
Reputation: 30718
You can use Process.GetProcesses to get processes by name
var processes = Process.GetProcesses Method (ProcessName)
if (processes!= null)
{
int runningInstances = processes.Length;
}
Upvotes: 0