tags:

views:

205

answers:

3

So I've found this information http://stackoverflow.com/questions/229565/what-is-a-good-pattern-for-using-a-global-mutex-in-c/229567

But it's based on the main entry point of a standard app. How do you modify this to work for the WPF event model of starting the app?

A: 

When I first answered this, I read and wrote WPF, but thought "WCF". Stupid me. Here's my new answer:

If it has to be truly global, put your mutex setup in any early event that precedes any use of the shared resource. Application.Startup is probably your best bet.

Randolpho
A: 

Are you asking this to create a single instance WPF application? If so, I encourage you to take a look at this project I created on CodePlex. It provides an Application derived class that incapsulates the logic to create a single-instance/multiple-instance aware WPF application, dealing with inter-instances communication too (i.e. the main application can receive the arguments passed to a subsequent instance). The source code is available, so you can even check that a global mutex and some WaitHandle are used to ensure synchronization.

To answer directly to your question, the proper place to acquire the global mutex is inside an override of the Application.Startup method, since it is called at the beginning (more or less) of the Application.Run method, which can be considered equivalent to the program Main (of course it is not the same thing, but for the purpose of having a single instance application is enough).

BladeWise
A: 

It looks like the big issue is that when Startup is called by default it calls Show() on the main form.

Since this means the function returns, wrapping the Startup call in the mutex like the original example I linked, the lock on the mutex is released shortly after startup. If you either change the way Statup opens the main from from Show() to ShowDialog() it works as expected.

Joel Barsotti