Monitor.TryEnter doesn't work

c#, multithreading, wpf

Solution

Mixing `Monitor` and `await` is... more than a little risky. It looks like what you are trying to do is to ensure it only runs once at a time. I suspect `Interlocked` may be simpler:

object _sync = new object();
int running = 0;
private async void OnKeyDown(object sender, KeyEventArgs e) {
    if(Interlocked.CompareExchange(ref running, 1, 0) != 0) return;

    Trace.Write("taken...");
    await Task.Delay(TimeSpan.FromSeconds(5));
    Trace.WriteLine(" done");

    Interlocked.Exchange(ref running, 0);
}

Note you might also want to think what happens if an error occurs etc; how does the value become reset? You can probably use `try`/`finally`:

if(Interlocked.CompareExchange(ref running, 1, 0) != 0) return;

try {
    Trace.Write("taken...");
    await Task.Delay(TimeSpan.FromSeconds(5));
    Trace.WriteLine(" done");
} finally {
    Interlocked.Exchange(ref running, 0);
}

Problem

Part of my code-behind: ``` object _sync = new object(); private async void OnKeyDown(object sender, KeyEventArgs e) { if (!Monitor.TryEnter(_sync)) return; Trace.Write("taken..."); await Task.Delay(TimeSpan.FromSeconds(5)); Trace.WriteLine(" done"); Monitor.Exit(_sync); } ``` Output (pressing several times in less than 5 seconds): ``` taken...taken...taken... done done done ``` How-come?? the `_sync` lock is never being taken, why?

Original source