using System.text;
using System.Threading;
using System.Reflection;
#endregion
public class TestApplication
{
#region Private Fields
The default instance
private static TestApplication DefValue = new TestApplication ();
The system-wide semaphore
private Semaphore semaphore;
Initial count for the semaphore(Randonm you can choose any big count)
private const int MAXCOUNT = 10000;
private static bool _pvInstance ;
#endregion
#region Properties
The PrevInstance property returns True if there was a previous instance running when the default instance was created
public static bool PrevInstance
{
get
{
return _pvInstance ;
}
}
Return the total number of instances of the same application that are currently running
public static int InstanceCount
{
get
{
// release the semaphore and grab the previous count
int prevCount = DefValue.semaphore.Release();
// acquire the semaphore again
DefValue.semaphore.WaitOne();
// evaluate number of other instances that are currently running.
return MAXCOUNT - prevCount;
}
}
#endregion
Constructor.
private TestApplication ()
{
// create a named (system-wide semaphore)
bool ownership = false;
// create the semaphore or get a reference to an existing semaphore
string appName = "TestApplication _" + Assembly.GetExecutingAssembly().Location.Replace(":", string.Empty).Replace("\\", string.Empty);
semaphore = new Semaphore( MAXCOUNT, MAXCOUNT, appName , out ownership);
// decrement its value
semaphore.WaitOne();
// if we got ownership, this app has no previous instances
_prevInstance = !ownership;
}
Destructor to destroy.
~TestApplication ()
{
// increment the semaphore when the application terminates
semaphore.Release();
}
}
Is credit due to Francesco Balena?
ReplyDelete