Another cross-language question: can someone tell me what C# Threading constructs best match the Java ReentrantLock and Condition classes? ReentrantLock has lockInterruptibly() and unlock() methods, while Condition has signal() and await() methods. It is this combination that I would like to be able to preserve in the C# code - or something similar... Thanks in advance.
3 Answers
I think what you're looking for is the static Monitor class. I allows for blocking and non-blocking mutex acquisition, as well as condition variable operations. (They call them Pulse, PulseAll and Wait rather than signal and await).
-
Seems to be working for me! Thanks! Another question: does Monitor provide a counterpart to Java isHeldByCurrentThread() ? Mar 11, 2009 at 15:39
-
1No, you could extend Monitor and keep a reference to the Thread which last successfully called Enter or TryEnter. The current thread can be accessed using Thread.CurrentThread: msdn.microsoft.com/en-us/library/…– Ben SMar 11, 2009 at 17:08
-
@BenS, what the C# equivalent be of Java
taskEnded.await(10, TimeUnit.SECONDS);
wheretaskEnded
is of typejava.util.concurrent.locks.Condition
.Monitor.Wait
doesn't seem to match. Mar 7, 2019 at 3:43
The ReaderWriterLock class would also be worth looking into. This is similar to ReentrantReadWriteLock in Java.
-
+1 for pointing out the similarity. But MSDN recommends using ReaderWriterLockSlim over
ReaderWriterLock
. Nov 12, 2017 at 11:32
DISCLAIMER: I don't know these Java classes, I'm taking a stab in the dark here.
In C#, you have a lock
statement (I think this is something like Java's synchronized
statement) which can lock on any object. I suppose using that statement, or Monitor.Enter(obj)
and Monitor.Exit(obj)
would be a bit like ReentrantLock.
There are two class called ManualResetEvent
and AutoResetEvent
. These classes have a Wait
method, and a Set
method, which I suppose is like Condition's signal and await. The difference between these two classes is that a ManualResetEvent
stays set (no longer blocking anyone) and must be Reset
. And AutoResetEvent
is - like its name suggests - reset automatically.
-
Cannot use lock in async statement and Monitor methods needs to be called from synchronized thread.. the point of Java's ReentrantLock is to make those issues go away. Jan 28, 2018 at 18:11
-
1Seeing as async methods didn't exist in either C# or Java when this question was asked, I think that's hardly the point of ReentrantLock, or at least not the point the asker was referring to. Feb 1, 2018 at 0:11