I need to try to lock on an object, and if its already locked just continue (after time out, or without it).
The C# lock statement is blocking.
I had the same problem, I ended up creating a class TryLock that implements IDisposable and then uses the using statement to control the scope of the lock:
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..");
}
}