封装一个MTA的WaitALL
class MtaWaitAllWrapper {
readonly WaitHandle[] waitHandles;
readonly int millisecondsTimeout;
bool waitResult;
Exception error;
MtaWaitAllWrapper(int millisecondsTimeout,
params WaitHandle[] waitHandles) {
if (waitHandles == null) throw new ArgumentNullException(@"waitHandles");
this.waitHandles = waitHandles;
this.millisecondsTimeout = millisecondsTimeout;
}
void WaitAll() {
if ((waitHandles.Length > 1) && (Thread.CurrentThread.GetApartmentState() != ApartmentState.MTA)) {
Thread thread = new Thread(new ThreadStart(OnWaitAll));
thread.SetApartmentState(ApartmentState.MTA);
thread.Start();
thread.Join();
} else {
OnWaitAll();
}
}
void OnWaitAll() {
try {
waitResult = WaitHandle.WaitAll(waitHandles, millisecondsTimeout, false);
} catch (Exception ex) {
error = ex;
}
}
public static bool WaitAll(int millisecondsTimeout,
params WaitHandle[] waitHandles) {
MtaWaitAllWrapper waitAllWrapper =
new MtaWaitAllWrapper(millisecondsTimeout, waitHandles);
waitAllWrapper.WaitAll();
if (waitAllWrapper.error != null) throw waitAllWrapper.error;
return waitAllWrapper.waitResult;
}
}