12

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 3

9

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).

3
  • Seems to be working for me! Thanks! Another question: does Monitor provide a counterpart to Java isHeldByCurrentThread() ? Mar 11, 2009 at 15:39
  • 1
    No, 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 S
    Mar 11, 2009 at 17:08
  • @BenS, what the C# equivalent be of Java taskEnded.await(10, TimeUnit.SECONDS); where taskEnded is of type java.util.concurrent.locks.Condition. Monitor.Wait doesn't seem to match. Mar 7, 2019 at 3:43
1

The ReaderWriterLock class would also be worth looking into. This is similar to ReentrantReadWriteLock in Java.

1
0

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.

2
  • 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.
    – Vistritium
    Jan 28, 2018 at 18:11
  • 1
    Seeing 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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.