user1390652 user1390652 - 1 month ago 22
C# Question

My Mutex is not working

private static bool Created;
private static System.Threading.Mutex PaintGuard = new System.Threading.Mutex(false, "MonkeysUncleBob", out Created);

//Function that is attached to each pages "LayoutUpdated" call.
private async void AnyPageLayoutUpdated(object sender, object e)
{
if (Created)
{

PaintGuard.WaitOne();
try
{
await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
() =>
{
LCDDriver.ILI9488.PaintScreen(sender);
});
}
catch (Exception f)
{

}
finally
{
PaintGuard.ReleaseMutex();
}
}
}


The problem is that somehow multiple threads can enter into the code still.
I have verified this by using the debugger, and I can see multiple threads entering into the try before executing the finally.

I must be using it wrong.

Answer

await is not compatible with Mutex. You can use an async-compatible mutex like SemaphoreSlim or the AsyncLock that I have as part of my AsyncEx library.

However, if you need a named mutex, then you'll have to do something quite different. What that is depends on what exactly you're trying to do.