Reputation: 1297
I have a question when it comes to create a "System Wide Mutex" that will work with many instances of the same application.
So I want a process to be threadsafe as seen in the code where I write to the same file:
Write to the same file
I wonder if I do set this up programatically correct. For example I release the mutex when I close the form. I also set the bool to true (InitiallyOwned) for the mutex when I do create it?
I have tried to google this but are not sure I get a clean answer to it. The use case would be to be able to open and close instances at random and always have the mutex in place.
public Form1()
{
try
{
_mutex = System.Threading.Mutex.OpenExisting("systemWideMutex");
_mutex.WaitOne(); //obtain a lock by waitone
_mutex.ReleaseMutex(); //release
}
catch { _mutex = new System.Threading.Mutex(true, "systemWideMutex"); } //Create mutex for the first time
new Thread(threadSafeWorkBetween2Instances).Start(); //Start process
}
void threadSafeWorkBetween2Instances()
{
while (true)
{
try
{
_mutex = System.Threading.Mutex.OpenExisting("systemWideMutex");
_mutex.WaitOne(); //obtain a lock by waitone
//DO THREADSAFE WORK HERE!!!
//Write to the same file
_mutex.ReleaseMutex(); //release
}
catch { _mutex = new System.Threading.Mutex(true, "systemWideMutex"); } //Create mutex for the first time
Thread.Sleep(10000);
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
_mutex.ReleaseMutex(); //release
}
Upvotes: 0
Views: 3100
Reputation: 1475
Try something like this:
System.Threading.Mutex _mutex = null;
bool mutexWasCreated = false;
public Form1()
{
new Thread(threadSafeWorkBetween2Instances).Start();
}
void threadSafeWorkBetween2Instances()
{
if(!_mutex.TryOpenExisting("GlobalsystemWideMutex"))
{
// Create a Mutex object that represents the system
// mutex named with
// initial ownership for this thread, and with the
// specified security access. The Boolean value that
// indicates creation of the underlying system object
// is placed in mutexWasCreated.
//
_mutex = new Mutex(true, "GlobalsystemWideMutex", out
mutexWasCreated, mSec);
if(!mutexWasCreated )
{
//report error
}
}
while (true)
{
try
{
bool acquired = _mutex.WaitOne(5000); //obtain a lock - timeout after n number of seconds
if(acquired)
{
try
{
//DO THREADSAFE WORK HERE!!!
//Write to the same file
}
catch (Exception e)
{
}
finally
{
_mutex.ReleaseMutex(); //release
break;
}
}
else
{
Thread.Sleep(1000); // wait for n number of seconds before retrying
}
}
catch { } //Create mutex for the first time
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
try { _mutex.ReleaseMutex(); } catch { } //release
}
Upvotes: 1