A solution to "WaitAll for multiple handles on an STA thread is not supported."

  • Thread starter Thread starter isbat1
  • Start date Start date
I

isbat1

Seems like a lot of people have trouble with this error. Here's my
solution. I give it to the future. Because I love you.

private void WaitAll(WaitHandle[] waitHandles) {
if (Thread.CurrentThread.ApartmentState == ApartmentState.STA) {
// WaitAll for multiple handles on an STA thread is not supported.
// ...so wait on each handle individually.
foreach(WaitHandle myWaitHandle in waitHandles) {
WaitHandle.WaitAny(new WaitHandle[]{myWaitHandle});
}
}
else {
WaitHandle.WaitAll(waitHandles);
}
}
 
Seems like a lot of people have trouble with this error. Here's my
solution. I give it to the future. Because I love you.

private void WaitAll(WaitHandle[] waitHandles) {
if (Thread.CurrentThread.ApartmentState == ApartmentState.STA) {
// WaitAll for multiple handles on an STA thread is not supported.
// ...so wait on each handle individually.
foreach(WaitHandle myWaitHandle in waitHandles) {
WaitHandle.WaitAny(new WaitHandle[]{myWaitHandle});
}
}
else {
WaitHandle.WaitAll(waitHandles);
}
}

That seems to change the behaviour entirely though - isn't it actually
waiting for *all* of the handles, just sequentially?
 
Jon Skeet said:
That seems to change the behaviour entirely though - isn't it actually
waiting for *all* of the handles, just sequentially?

Doh - ignore me. I thought you were trying to mimic Wait*Any* by
calling it multiple times.

Why use WaitAny with an array rather than calling WaitOne directly on
each handle? That would seem somewhat simpler to me.
 
Jon Skeet said:
Doh - ignore me. I thought you were trying to mimic Wait*Any* by
calling it multiple times.

Why use WaitAny with an array rather than calling WaitOne directly on
each handle? That would seem somewhat simpler to me.

And another point (which I must admit was pointed out to me by Ian
Griffiths - I won't take credit for it) - the whole point of WaitAll is
that it's an atomic acquisition, effectively. You unfortunately lose
the atomicity in your call, so you could introduce deadlocks which
wouldn't otherwise be present.
 
Well, since you can't do a WaitAll from an STA thread, the only other
thing I know to do is to wait for each wait handle individually. Have
I misunderstood something?
 
Myopic thinking. I was fixated on getting a method from WaitHandle to
work. I blame my antibiotics.
 
Back
Top