I create a mutex within the OnStartup
Method of a WPF app. The mutex is not used anywhere else in the program, its only purpose is to prevent certain programs from
According to my research, every GUI WPF application has a UI thread which can be accessed via Application.Current.Dispatcher
(see for example this answer). This UI thread should always remain active for the lifetime of the application.
You can use Dispatcher.CheckAccess
to see whether you are running in the UI thread, and if you are not you can use Dispatcher.Invoke
to execute an action in the context of the UI thread.
The description of Application.Run implies that Application.OnStartup
is always run on the UI thread, but it should not be harmful to check and, if necessary, use the UI thread dispatcher to invoke the action that creates the mutex.
It seems a reasonable guess that Application.OnExit
is also always run on the UI thread, but since this does not appear to be documented, you should check and, if necessary, use the UI thread dispatcher to invoke the action that releases the mutex.
As Alexm correctly points out, you do not in fact need to explicitly release the mutex provided that the application is running in its own process (which will usually be the case) but you do need to ensure that the thread the mutex is created on will remain active until you are ready to free it. I believe using the UI thread is the simplest way to ensure this.
I personally wouldn't bother releasing it at all, especially since you handle AbandonedMutexException
.
If a mutex is not used to synchronize threads of the same process there is no need to explicitly release it. When a process terminates OS automatically closes all handles created by the process, such as files, sockets, mutexes, semaphores and event handles .
If you still prefer to release it consider using Application.OnExit()
since it is called from the main thread, just like the Startup()
.