0

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 OpenExistingand TryOpenExisting but to no avail.

Community
  • 1
  • 1
kernanb
  • 566
  • 2
  • 6
  • 19

1 Answers1

1

You are not locking your mutex in main app, you just create it (also without ownership). You can either create Mutex with initial ownership or call WaitOne() when needed. Some more help at Joe Alabhari's blog.

public void Application_Launching(object sender, LaunchingEventArgs e)
{
    var myMutex = new Mutex(true, "MUTEX_NAME");
    // or call myMutex.WaitOne() // here maybe some timeout handling
}

Also I don't think that holding a mutex until the app is closed is a good practise - lock the mutex only when you really need to (for example access to common file). If you really want to try this, create a global mutex instance upon launching, then release it upon closing, but without obtaining it again, just use previous instance.

Look out for couple of things - don't leave abandoned mutexes, look out so it's not garbage collected, release it when needed. There are plenty of posts about this synchronization object, here you have a good pattern.

Community
  • 1
  • 1
Romasz
  • 29,662
  • 13
  • 79
  • 154
  • Thanks that worked! A follow up question, if the foreground app crashes will the mutex get released? – kernanb Nov 06 '15 at 21:57
  • 1
    @kernanb No, it won't be automatically release. Take a look at the patterns - relesing is in every case in *finally* block, in that case mutex is released regardless there was exception or not. – Romasz Nov 06 '15 at 22:01