In the most compact frame there.
What is the use of Mutex if you cannot name it?
An unnamed mutex is called a local mutex. You can use it to synchronize between different threads in the same process. A monitor, such as the lock
keyword, does not have the same number of functions. As ctacke notes, Mutex does not allow recursive input. In addition, the monitor cannot be used within the boundaries of the AppDomain. In addition, Mutex can be used with useful things like WaitHandle.WaitAll or WaitAny
, where the monitor cannot be used with any of these things.
Did I miss something?
Not. In the .NET CF Framework, you cannot name a mutex without the help of a platform.
How to use a mutex to protect a resource for several applications if I cannot name them?
You have to name them - and you can do it, you just need to resort to some invoke platform. On Windows CE, it is supported with the name mutexes for a while. You can write a P / Invoke call that does this on its own:
[DllImport("Coredll.dll")] public static extern IntPtr CreateMutex(IntPtr lpMutexAttributes, bool initialOwner, string lpName);
And use it like (for example) CreateMutex(IntPtr.Zero, false, "MutexName");
You will also have to write P / Invoke calls for ReleaseMutex
and CloseHandle
.
In particular, I want to make a single-user application for Windows Mobile 6.5.
A named mutex is one solution. Another solution that might work for you is to use file lock.
- Create a file called foo.txt at startup if it does not exist.
- Get a write lock on a file using
FileShare.None
. - Another instance will not be able to use write lock because the first instance has a lock and will not share it. Catch the exception and exit the program since it is already running.
When the program closes, clear the lock. Even if the process crashes or aborts abnormally, the file lock must be removed in order to start another instance. Something like that:
FileStream stream; try { stream = new FileStream("lock.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None); } catch { MessageBox.Show("Program is already running."); return; }
source share