I want to prevent my Background Process from performing an action if the app is open in the foreground. I found a similar question posed here, but I can't get it to work for me. When my Background Process checks the Mutex, it is never already in existence. When the foreground app starts I create a Mutex like so:
public void Application_Launching(object sender, LaunchingEventArgs e)
{
var myMutex = new Mutex(false, "MUTEX_NAME");
}
I release it when the foreground app closes:
private void Application_Closing(object sender, ClosingEventArgs e)
{
var myMutex = new Mutex(false, "MUTEX_NAME");
myMutex.ReleaseMutex();
}
In the Background Process I have the following check:
bool IsMutexLocked()
{
var myMutex = new Mutex(false, "MUTEX_NAME");
return myMutex.WaitOne(100);
}
I'm assuming here that WaitOne
returns true if "MUTEX_NAME"
doesn't exist, or it does exist but gets released after 100ms. I've also tried using the out createdNew
in the Mutex constructor, and the static methods OpenExisting
and TryOpenExisting
but to no avail.