What (I think) I want is the equivelant of an AutoResetEvent
that multiple threads can wait on, all to be resumed when it's set.
I know this can be achieved by having one AutoResetEvent
per thread and setting each of them - but is there an easier way? A way that doesn't depend on arrays of eventhandles?
Effectively what (I think) I'd like is to be able to do this:
private volatile string state;
private MultiEventHandle stateChanged = new MultiEventHandle();
public void WaitForBlob()
{
while (true)
{
object saved = stateChanged.Current; // some sentinel value
if (state == "Blob") break;
stateChanged.WaitTilNot(saved); // wait til sentinel value != "current"
}
}
public void SetBlob()
{
state = "Blob";
stateChanged.Change(); // stateChanged.Current becomes a new sentinel object
}
ie, any number of threads can call WaitForBlob
, and at any time (no race conditions) SetBlob
can be called by yet another thread, and all waiting threads will detect the change immediately - and importantly, with no spin locks or Threading.Sleeps.
Now I think I can implement a "MultiEventHandle
" relatively easily. But my question is... is there a better way? Surely I'm going about this wrong as it must be a pretty common use case, but I can't seem to find an in-built tool for the job. I'm afraid I may be going about inventing a square wheel here..