zoukankan      html  css  js  c++  java
  • WaitAll for multiple handles on a STA thread is not supported 解决方案

    封装一个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;
            }
        }

  • 相关阅读:
    第十三周助教作业
    【西北师大-19软工】第五次作业成绩汇总
    第十二周助教工作总结
    第十一周助教工作总结
    第九周助教工作总结
    第八周助教工作总结
    第七周助教工作总结
    SQLAlchemy 学习笔记(二):ORM 基础
    WebSocket 与 HTTP/2
    Chrome 与 Firefox-Dev 的 DevTools
  • 原文地址:https://www.cnblogs.com/xixifusigao/p/2247943.html
Copyright © 2011-2022 走看看