Requirement:
A. 1 user login can open 0-1 System.Windows.Form
instances on 1 physical machine in ProcessName
.
B. 2 different user logins are each able to open 0-1 System.Windows.Form
instances on 1 physical machine in ProcessName
.
C. MutexChecker
is in its own class rather than a member of Form
because the responsibility for disposing of the Mutex changes from one form to a different form based on user actions.
D. Said Form
's are launched asynchrously after the creation of the Mutex. So I cannot implement a using
statement.
Problem:
On other SO posts, I've seen code similar to the below labeled as "unsafe". However, the reasons for the code being labeled "unsafe" are not given. Rather, a global mutex is offered as the solution. A global mutex works machine-wide, therefore it does not meet the requirement.
What I have tried:
Call mutexChecker.RunCheck()
from said System.Windows.Form
public class MutexChecker:IDisposable
{
private Mutex mutex;
public bool RunCheck()
{
bool createdNew;
mutex = new Mutex(initiallyOwned: true, name: "AppName", createdNew: out createdNew);
if (!createdNew)
{
MessageBox.Show("AppName is already running. Please complete the other note before opening a new window.");
}
return createdNew;
}
public void Dispose()
{
mutex.ReleaseMutex();//ERROR: safe handle has been disposed
mutex.Dispose();//Does not always release the mutex for some unknown reason
}
Dispose on the mutex during Form.Dispose
.
Question
How can I safely create a mutex that fulfills the requirement?