views:

529

answers:

3

Are condition variables & monitors used in C#?

Can someone give me an example?

+2  A: 

You can use the Lock object which acts as syntactic sugar for the Monitor class.

lock(someObject)
{
    // Thread safe code here.
}

http://msdn.microsoft.com/en-us/library/c5kehkcz%28VS.80%29.aspx

Aequitarum Custos
One small correction, it is not an object, but a keyword, and is spelled lowercase, `lock` :)
Skurmedel
Thanks, been developing in VB.NET at work, so had SyncLock on the brain and just removed the Sync part heh.
Aequitarum Custos
+2  A: 

System.Threading.Monitor is one way (example within)

jspcal
+4  A: 

The direct equivalent of a condition variable in .NET is the abstract WaitHandle class. Practical implementations of it are the ManualResetEvent, AutoResetEvent, Mutex and Semaphore classes.

System.Threading.Monitor is the direct equivalent of a monitor. The lock statement makes it very easy to use, it ensures the monitor is always exited without explicitly programming the Exit() call.

Hans Passant
Note that exiting a monitor if code throws an exception is not necessarily a good thing; the monitor was probably protecting a mutation to ensure that the result upon exiting the monitor was consistent; an exception is evidence that the mutation was only partially completed and therefore you've just unlocked access to inconsistent state. If the exception is caught and the program continues then you cannot rely upon the program state being consistent.
Eric Lippert
Very good point, I re-worded that. Thanks.
Hans Passant