views:

423

answers:

3

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  A: 

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

Ben S
Seems to be working for me! Thanks! Another question: does Monitor provide a counterpart to Java isHeldByCurrentThread() ?
Paul Morrison
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: http://msdn.microsoft.com/en-us/library/system.threading.thread.currentthread.aspx
Ben S
A: 

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.

configurator
A: 

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

Taylor Leese