C# equivalent to java's wait and notify?

C#JavaMultithreading

C# Problem Overview


I am aware that you can lock an object in c# using lock but can you give up the lock and wait for something else to notify you that it's changed like you can in java with wait and notify?

It seems to me that synchronised and lock in java and c# respectively are synonomous.

C# Solutions


Solution 1 - C#

The equivalent functionality (including the normal locking) is in the Monitor class.

foo.notify() => Monitor.Pulse(foo)
foo.notifyAll() => Monitor.PulseAll(foo)
foo.wait() =>  Monitor.Wait(foo)

The lock statement in C# is equivalent to calling Monitor.Enter and Monitor.Exit with an appropriate try/finally block.

See my threading tutorial or Joe Albahari's one for more details.

Solution 2 - C#

I think Wait Handles may work for you. See if this helps.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionOmar KoohejiView Question on Stackoverflow
Solution 1 - C#Jon SkeetView Answer on Stackoverflow
Solution 2 - C#EBGreenView Answer on Stackoverflow