No semaphore to count. currently running instances

I am working on a multi-user application. Is there a way in C # to know how many instances are currently running.
I used one piece of code to count the window processes of the name of my application, but this is not very good.

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);


This can be done using a semaphore or increment and decrement counter, which increases by one when creating a new instance and decreases by one when closing the instance.

+5
source share
3 answers

A Semaphore , , 0. , .

, , , , .

+1

? , , , .

, P/Invoke, , .

+1

. , - . , , , . AppDomains .NET-, , , , .

, , . , - , . - , , , . - , , .

, Process.Exited . .

+1

All Articles