Exemplo n.º 1
0
        public DispatcherPool(string name, int threadCount, Func <object> tagGenerator)
        {
            Verify.IsNeitherNullNorEmpty(name, "name");
            Verify.BoundedInteger(1, threadCount, 10, "threadCount");
            _masterDispatcher = Dispatcher.CurrentDispatcher;

            _asyncDispatchers = new Dispatcher[threadCount];
            _dispatcherTags   = new Dictionary <int, object>();

            for (int i = 0; i < _asyncDispatchers.Length; ++i)
            {
                var dispatcherThread = new Thread(_DispatcherThreadProc);
                dispatcherThread.SetApartmentState(ApartmentState.STA);
                if (_asyncDispatchers.Length > 1)
                {
                    dispatcherThread.Name = name + " (" + (i + 1).ToString() + ")";
                }
                else
                {
                    dispatcherThread.Name = name;
                }

                using (var dispatcherCreated = new AutoResetEvent(false))
                {
                    dispatcherThread.Start(dispatcherCreated);
                    dispatcherCreated.WaitOne();
                }

                Dispatcher currentDispatcher = Dispatcher.FromThread(dispatcherThread);
                _asyncDispatchers[i] = currentDispatcher;

                // When the thread that created this starts to shut down, shut down this as well.
                _masterDispatcher.ShutdownStarted += (sender, e) => currentDispatcher.BeginInvokeShutdown(DispatcherPriority.Normal);

                Assert.IsNotNull(_asyncDispatchers[i]);

                if (tagGenerator != null)
                {
                    _dispatcherTags.Add(currentDispatcher.Thread.ManagedThreadId, tagGenerator());
                }
            }
        }