Martin Christiansen
Martin Christiansen

Reputation: 1117

C# Which synchronization class to use?

I have the following synchronization problem to solve:

Multiple threads occationally check if a certain condition is fulfilled. If a checking thread finds that the condition is not fulfilled, it must block itself until another thread fulfills the condition and thereby releases all waiting/blocked threads.

Does .NET have such an out-of-the-box syncrhonizing class that I can use? Or will I have to build my own synchronization class on top of something else?

What I need is a simple semaphore-like class with only these two methods:

Regards, Martin.

Upvotes: 0

Views: 142

Answers (2)

MNGwinn
MNGwinn

Reputation: 2394

AutoResetEvent does what you're asking for.

Ah. I misunderstood what you were asking. A ManualResetEvent or a ManualResetSlim will let all the blocking threads through, but you'll need to reset the MRE to unsignalled manually.

Upvotes: 0

David
David

Reputation: 10708

EventWaitHandle sounds like what you are looking for. Keep in mind that as you get into such specific implementations, you might be better off making a wrapper class to do what you want by hooking into the disparate .NET classes that do the parts of what you want.

By using an auto-resetting behavior, you can make a handle which is fired every time something about said condition changes, and then perform a while loop against the condition

EventWaitHandle ConditionHandle
//...
while(!condition)
    ConditionHandle.WaitOne();

Upvotes: 1

Related Questions