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

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);
}
}
 
J

Jon Skeet [C# MVP]

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?
 
J

Jon Skeet [C# MVP]

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.
 
J

Jon Skeet [C# MVP]

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.
 
I

isbat1

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?
 
I

isbat1

Myopic thinking. I was fixated on getting a method from WaitHandle to
work. I blame my antibiotics.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top