What's the correct pattern for using a global mutex in WPF?
So I found this information What is a good pattern for using Global Mutex in C #?
But it is based on the main entry point of a standard application. How do you change this to work for the WPF event model to start the application?
a source to share
It looks like the big problem is that when Startup is called by default, it calls Show () on the main form.
Since this means that the function returns by completing the Startup call on the mutex, like the original example I linked, the lock on the mutex will be released shortly after starting. If you either change the way Statup opens the main line from Show () to ShowDialog (), it works as expected.
a source to share
When I first answered this, I read and wrote WPF but thought "WCF". Stupid me. Here's my new answer:
If it needs to be truly global, set the mutex setting to any early event that precedes the use of the share. Application.Startup
is probably your best bet.
a source to share
Are you asking for this to create a single user WPF application ? If so, I recommend that you take a look at this project I created on CodePlex. It provides a derived class Application
that encapsulates the logic to create a single / multi-instance WPF application that also uses inter-instance communication (i.e., the main application can accept arguments passed to a subsequent instance). Source code is available, so you can even check that global mutexes and some WaitHandle are used to ensure synchronization.
To answer directly to your question, the proper place to get a global mutex is inside a method override Application.Startup
, since it is called at the beginning (more or less) of a method Application.Run
, which can be considered program equivalent Main
(of course, they are not the same thing, but in order to to have just one instance of the application).
a source to share
Quick response:
In App.xaml: change application to InstanceAwareApplication
In App.xaml.cs: change app to InstanceAwareApplication and override OnStartup (StartupEventArgs e, bool isFirstInstance)
Then follow the example: http://wpfinstanceawareapp.codeplex.com/SourceControl/changeset/view/53538#530411
a source to share