I am working on multi instance application. Is there any way in c# to know that how many instances are running currently.
I used one peice of code to count the window processes of my application name but that is not a good way.
string fileName = Process.GetCurrentProcess().MainModule.FileName;
int count = 0;
foreach (Process p in Process.GetProcesses())
{
try
{
if (p.MainModule.FileName == fileName)
{
count++;
}
}
catch { }
}
MessageBox.Show("Total Instances Running are " + count);
Can it be done by using semaphore or some increment and decrement counter that is incremented by one when new instance is created and decrement by one when a instance closes.
A
Semaphorehelps you count down, blocking you when you get to 0. You could use a global semaphore, but you’ll have to initialize it at a high enough-value and start counting down.I think all in all, your own solution is probably the cleanest.