I had the same problem, I ended up creating a TryLock class that implements IDisposable, and then uses the using statement to control the lock area:
public class TryLock : IDisposable { private object locked; public bool HasLock { get; private set; } public TryLock(object obj) { if (Monitor.TryEnter(obj)) { HasLock = true; locked = obj; } } public void Dispose() { if (HasLock) { Monitor.Exit(locked); locked = null; HasLock = false; } } }
And then use the following syntax to lock:
var obj = new object(); using (var tryLock = new TryLock(obj)) { if (tryLock.HasLock) { Console.WriteLine("Lock acquired.."); } }
cwills May 19 '14 at 12:22 a.m. 2014-05-19 00:22
source share