Is there a "try to block, skip if time-out" operation in C #?

I need to try to lock the object, and if it is already locked, just continue (after or without a timeout).

The C # lock statement blocks.

+53
multithreading c # locking
Aug 12 '08 at 6:19 06:19
source share
5 answers

I believe you can use Monitor.TryEnter() .

The lock statement is simply converted to a call to Monitor.Enter() and a try catch .

+34
Aug 12 '08 at 6:29
source share

Ed got the right function for you. Just remember to call Monitor.Exit() . You must use a try-finally block to ensure that it cleans properly.

 if (Monitor.TryEnter(someObject)) { try { // use object } finally { Monitor.Exit(someObject); } } 
+79
Aug 12 '08 at 6:37
source share

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.."); } } 
+9
May 19 '14 at
source share

You will probably find out now when others have pointed you in the right direction, but TryEnter can also accept a timeout parameter.

Jeff Richter "CLR Via C #" is a great book about the details of the internal properties of the CLR if you find yourself in more complex things.

+3
Aug 12 '08 at 7:54
source share
0
03 Feb '17 at 18:15
source share



All Articles