When implementing Inter-Process Communication (IPC) in .NET, Mutex
and MemoryMappedFile
are common and powerful tools. However, access issues can arise when one of the processes is a Windows Service due to permission differences. This article explains how to set permissions correctly and highlights a critical consideration when using a Mutex
.
The Mutex
and await
Pitfall
A crucial rule when working with a Mutex
is that the lock must be acquired and released on the same thread.
Mutex.WaitOne()
blocks the current thread until the lock is acquired, and Mutex.ReleaseMutex()
releases it. If you use the await
keyword between WaitOne()
and ReleaseMutex()
, the code after the await
may be executed by a different thread from the thread pool. If this happens, ReleaseMutex()
will be called on a thread that does not own the lock, throwing an ApplicationException
.
Warning: You must not perform an
await
operation between theMutex.WaitOne()
andMutex.ReleaseMutex()
methods.
Permission Control with Windows Services
Permission issues often occur during IPC between a standard desktop application and a Windows Service. This is because Windows Services typically run under accounts with different privileges, such as Local System
, Local Service
, or Network Service
, while a desktop app runs under the currently logged-in user’s account.
To allow these two processes to share named kernel objects like a Mutex
or MemoryMappedFile
, you need to explicitly set Access Control Lists (ACLs) for these objects.
The following example demonstrates how to grant the current user full control over a global Mutex
and MemoryMappedFile
.
|
|
By setting these permissions, both the application and the Windows Service can successfully access and synchronize with these shared kernel objects, even when running in different security contexts.