I'm currently writing a WPF app, that registers a url scheme which basically passes command line arguments to the app. Now the idea is to only start the app once and if an additional link is clicked, the first started app should evaluate the command line.
Since I've never done that with a Mutex I've read a few tutorials and now I've programmed it with Mutex
and a MemoryMappedFile
added to my App class like the following:
public partial class App : Application
{
Mutex m_Mutex;
MemoryMappedFile m_File;
protected override void OnStartup(StartupEventArgs e)
{
bool mutexCreated;
Assembly assembly = Assembly.GetExecutingAssembly();
string mutexName = $"local_{ assembly.GetType().GUID }";
m_Mutex = new Mutex(true, mutexName, out mutexCreated);
// Use user32.dll RegisterWindowMessage() to register a Message for the app.
m_File = MemoryMappedFile.CreateOrOpen($"{mutexName}_mappedData", /* Other Parameters like Security Settings etc. */ );
if(!mutexCreated)
{
m_Mutex = null;
m_File = null;
// Use user32.dll PostMessage() to broadcast to all Apps.
App.Current.Shutdown();
}
else
{
this.MainWindow = new MainWindow();
this.MainWindow.Show();
}
}
}
This now works fine and I can pass the data easily between applications using the PostMessage
broadcast.
Now the MSDN reference for the Mutex
class has a Destructor added in the example. The tutorial I've had didn't do that.
~App()
{
m_Mutex?.Dispose();
m_File?.Dispose();
}
I've tried it now compiling with and without the Destructor - even crashing the app on purpose, but I've not seen any difference. After the base instance of the app crashed, Windows seems to have disposed of the Mutex. At leased when I started the App again, it did create a new Mutex and the app started the new window. Any further app starts were correctly referencing that Mutex and messaging to the new window.
To me it seems that the GC is already cleaning up, with or without the finalizer in place. Now my question is, what exactly is the purpose of that specific Destructor, and is it necessary?