In the compact framework itself, no there is not.
What is the use for a Mutex if you can't name it?
An unnamed mutex is said to be a local mutex. You can still use it for synchronizing between different threads in the same process. A monitor like the lock
keyword doesn't have the same amount of functionality. As ctacke notes, a Mutex does not allow recursive entrance. Also, a monitor cannot be used across AppDomain boundaries. Additionally, a Mutex can be used with helpful things like WaitHandle.WaitAll or WaitAny
, where a monitor cannot be used with any of those things.
Am I missing something?
No - In the .NET CF Framework you cannot name a mutex without the help of platform invoke.
How do I use a mutex to protect a resource across multiple applications if I can't name them?
You have to name them - and you can do that, you just have to resort to some platform invoke. Windows CE based system have supported named mutexes for a while. You could write a P/Invoke call that does it yourself:
[DllImport("Coredll.dll")]
public static extern IntPtr CreateMutex(IntPtr lpMutexAttributes, bool initialOwner, string lpName);
And use it as (for example) CreateMutex(IntPtr.Zero, false, "MutexName");
You would also have to write P/Invoke calls for ReleaseMutex
and CloseHandle
.
Specifically I want to make my Windows Mobile 6.5 app single-instance.
A named mutex is one solution. Another solution that may work for you is to use a file lock.
- Create a file named foo.txt on start up if it doesn't exist.
- Acquire a write lock on the file file using
FileShare.None
.
- A different instance will not be able to aquire a write lock on it since the first instance has a lock on it and won't share it. Catch the exception and terminate the program since one is already running.
When the program closes, clean up the lock. Even if the process crashes or terminates abnormally, the lock on the file should be removed allowing another instance to start. Something like this:
FileStream stream;
try
{
stream = new FileStream("lock.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
}
catch
{
MessageBox.Show("Program is already running.");
return;
}
//Put your application code here.
MessageBox.Show("Program is now running.");
stream.Close();