Dispatcher Class
Definition
Provides services for managing the queue of work items for a thread.
Examples
The following example shows how to place an operation onto a Dispatcher. For the full source code of this example, see Single-Threaded Application with Long-Running Calculation Sample.
First, a delegate is created that accepts no arguments.
Next, BeginInvoke(DispatcherPriority, Delegate) is called. This call to BeginInvoke(DispatcherPriority, Delegate) takes two parameters: the priority, which is set to DispatcherPriority.Normal, and the callback, which is passed in through an instance of the delegate NextPrimeDelegate .
Remarks
The Dispatcher maintains a prioritized queue of work items for a specific thread.
When a Dispatcher is created on a thread, it becomes the only Dispatcher that can be associated with the thread, even if the Dispatcher is shut down.
If you attempt to get the CurrentDispatcher for the current thread and a Dispatcher is not associated with the thread, a Dispatcher will be created. A Dispatcher is also created when you create a DispatcherObject. If you create a Dispatcher on a background thread, be sure to shut down the dispatcher before exiting the thread.
If a Dispatcher is shut down, it cannot be restarted.
In WPF, a DispatcherObject can only be accessed by the Dispatcher it is associated with. For example, a background thread cannot update the contents of a Button that is associated with the Dispatcher on the UI thread. In order for the background thread to access the Content property of the Button, the background thread must delegate the work to the Dispatcher associated with the UI thread. This is accomplished by using either Invoke or BeginInvoke. Invoke is synchronous and BeginInvoke is asynchronous. The operation is added to the queue of the Dispatcher at the specified DispatcherPriority.
If BeginInvoke is called on a Dispatcher that has shut down, the status property of the returned DispatcherOperation is set to Aborted.
All of the methods on Dispatcher, with the exception of DisableProcessing, are free-threaded.
Objects that derive from DispatcherObject have thread affinity.
Objects that derive from Freezable are free-threaded when they are frozen. For more information, see Freezable Objects Overview.
Properties
Gets the Dispatcher for the thread currently executing and creates a new Dispatcher if one is not already associated with the thread.
Determines whether the Dispatcher has finished shutting down.
Determines whether the Dispatcher is shutting down.
Gets the collection of hooks that provide additional event information about the Dispatcher.
Gets the thread this Dispatcher is associated with.
Methods
Executes the specified delegate asynchronously with the specified arguments, at the specified priority, on the thread that the Dispatcher was created on.
Executes the specified delegate asynchronously with the specified arguments on the thread that the Dispatcher was created on.
Executes the specified delegate asynchronously at the specified priority on the thread the Dispatcher is associated with.
Executes the specified delegate asynchronously at the specified priority and with the specified argument on the thread the Dispatcher is associated with.
Executes the specified delegate asynchronously at the specified priority and with the specified array of arguments on the thread the Dispatcher is associated with.
Initiates shutdown of the Dispatcher asynchronously.
Determines whether the calling thread is the thread associated with this Dispatcher.
Disables processing of the Dispatcher queue.
Determines whether the specified object is equal to the current object.
(Inherited from Object)
Requests that all frames exit, including nested frames.
Gets the Dispatcher for the specified thread.
Serves as the default hash function.
(Inherited from Object)
Gets the Type of the current instance.
(Inherited from Object)
Executes the specified Action synchronously on the thread the Dispatcher is associated with.
Executes the specified Action synchronously at the specified priority on the thread the Dispatcher is associated with.
Executes the specified Action synchronously at the specified priority on the thread the Dispatcher is associated with.
Executes the specified Action synchronously at the specified priority on the thread the Dispatcher is associated with.
Executes the specified delegate at the specified priority with the specified arguments synchronously on the thread the Dispatcher is associated with.
Executes the specified delegate with the specified arguments synchronously on the thread the Dispatcher is associated with.
Executes the specified delegate within the designated time span at the specified priority with the specified arguments synchronously on the thread the Dispatcher is associated with.
Executes the specified delegate within the designated time span at the specified priority with the specified arguments synchronously on the thread the Dispatcher is associated with.
Executes the specified delegate synchronously at the specified priority on the thread that the Dispatcher is associated with.
Executes the specified delegate at the specified priority with the specified argument synchronously on the thread the Dispatcher is associated with.
Executes the specified delegate at the specified priority with the specified arguments synchronously on the thread the Dispatcher is associated with.
Executes the specified delegate synchronously at the specified priority and with the specified time-out value on the thread the Dispatcher was created.
Executes the specified delegate at the specified priority with the specified argument synchronously on the thread the Dispatcher is associated with.
Executes the specified delegate at the specified priority with the specified arguments synchronously on the thread the Dispatcher is associated with.
Executes the specified Action asynchronously on the thread the Dispatcher is associated with.
Executes the specified Action asynchronously at the specified priority on the thread the Dispatcher is associated with.
Executes the specified Action asynchronously at the specified priority on the thread the Dispatcher is associated with.
Initiates the shutdown process of the Dispatcher synchronously.
Creates a shallow copy of the current Object.
(Inherited from Object)
Enters an execute loop.
Pushes the main execution frame on the event queue of the Dispatcher.
Returns a string that represents the current object.
(Inherited from Object)
Determines whether the specified DispatcherPriority is a valid priority.
Determines whether the calling thread has access to this Dispatcher.
Creates an awaitable object that asynchronously yields control back to the current dispatcher and provides an opportunity for the dispatcher to process other events.
Creates an awaitable object that asynchronously yields control back to the current dispatcher and provides an opportunity for the dispatcher to process other events. The work that occurs when control returns to the code awaiting the result of this method is scheduled with the specified priority.
Events
Occurs when the Dispatcher finishes shutting down.
Occurs when the Dispatcher begins to shut down.
Occurs when a thread exception is thrown and uncaught during execution of a delegate by way of Invoke or BeginInvoke.
Occurs when a thread exception is thrown and uncaught during execution of a delegate by way of Invoke or BeginInvoke when in the filter stage.
Extension Methods
Executes the specified delegate asynchronously with normal priority on the thread that the specified Dispatcher was created on.
Executes the specified delegate asynchronously with the specified priority on the thread that the specified Dispatcher was created on.
Executes the specified delegate synchronously with normal priority on the thread that the specified Dispatcher was created on.
Executes the specified delegate synchronously on the thread that the specified Dispatcher was created on, and stops execution after the specified time-out period.
Executes the specified delegate synchronously with the specified priority on the thread that the specified Dispatcher was created on, and stops execution after the specified time-out period.
Executes the specified delegate synchronously with the specified priority on the thread that the specified Dispatcher was created on.
Dispatcher Priority Перечисление
Определение
Описывает приоритеты, с которыми могут вызываться операции посредством Dispatcher. Describes the priorities at which operations can be invoked by way of the Dispatcher.
Значением перечисления является 2. The enumeration value is 2. Операции обрабатываются, когда приложение бездействует. Operations are processed when the application is idle.
Значением перечисления является 4. The enumeration value is 4. Операции обрабатываются после завершения всех остальных операций, которые не находятся в состоянии ожидания. Operations are processed after all other non-idle operations are completed.
Значением перечисления является 3. The enumeration value is 3. Операции обрабатываются после завершения фоновых операций. Operations are processed after background operations have completed.
Значением перечисления является 8. The enumeration value is 8. Операции обрабатываются с таким же приоритетом, как и привязка данных. Operations are processed at the same priority as data binding.
Значением перечисления является 0. The enumeration value is 0. Операции не обрабатываются. Operations are not processed.
Значением перечисления является 5. The enumeration value is 5. Операции обрабатываются с таким же приоритетом, как и ввод данных. Operations are processed at the same priority as input.
Значением перечисляемого типа является -1. The enumeration value is -1. Это недействительный приоритет. This is an invalid priority.
Значением перечисления является 6. The enumeration value is 6. Операции обрабатываются, когда завершены формирование структуры и отрисовка содержимого, но перед обработкой элементов с приоритетом ввода. Operations are processed when layout and render has finished but just before items at input priority are serviced. Именно на этой стадии генерируется событие Loaded. Specifically this is used when raising the Loaded event.
Значением перечисления является 9. The enumeration value is 9. Операции обрабатываются с обычным приоритетом. Operations are processed at normal priority. Это типичный приоритет приложений. This is the typical application priority.
Значением перечисления является 7. The enumeration value is 7. Операции обрабатываются с таким же приоритетом, как и отрисовка. Operations processed at the same priority as rendering.
Значением перечисления является 10. The enumeration value is 10. Операции обрабатываются перед другими асинхронными операциями. Operations are processed before other asynchronous operations. Это наивысший приоритет. This is the highest priority.
Значением перечисления является 1. The enumeration value is 1. Операции обрабатываются, когда система бездействует. Operations are processed when the system is idle.
Примеры
В следующем примере вызывается Dispatcher.BeginInvoke метод и передается делегат с одним аргументом. The following example calls the Dispatcher.BeginInvoke method and passes it a delegate with one argument. Приоритет имеет значение Normal . The priority is set to Normal .
Комментарии
Нет конкретного состояния системы или «время простоя», соответствующего ApplicationIdle и ContextIdle в текущей версии WPF. There is no specific system state or «idleness» corresponding to ApplicationIdle and ContextIdle in the current version of WPF. Оба значения по-прежнему являются допустимыми приоритетами; операция с приоритетом ContextIdle имеет более высокий приоритет, чем операция с приоритетом SystemIdle . Both are still valid priorities; an operation with a priority of ContextIdle has a higher priority than an operation with a priority of SystemIdle .
Объект не Dispatcher регулирует выполнение операции, если он превышает определенный процент ресурсов ЦП. The Dispatcher does not throttle the execution of an operation if it exceeds a certain percentage of the CPU. Одним из способов регулирования процесса является использование таймера. One way to throttle a process is to use a timer.
System.Windows.Threading.Dispatcher и WinForms?
Работает ли System.Windows.Threading.Dispatcher пользовательский интерфейс приложения WinForms ?
Если да, то почему? Он поступает из WindowsBase.dll, который представляется компонентом WPF .
Если нет, как я могу вызвать рабочие единицы обратно на UI-поток? Я нашел Control.BeginInvoke() , но кажется неуклюжим создать элемент управления только для ссылки на исходный поток.
Вы можете использовать Dispatcher даже в приложении WinForms.
Если вы уверены, что находитесь в потоке пользовательского интерфейса (например, в обработчике button.Click), Dispatcher.CurrentDispatcher предоставляет диспетчер потоков пользовательского интерфейса, который позже можно использовать для отправки из потоков фона в поток пользовательского интерфейса, как обычно.
Dispatcher — это компонент WPF, а не компонент WinForms.
Если вы хотите отправлять рабочие элементы в поток пользовательского интерфейса, вам придется либо использовать Control.BeginInvoke, как вы уже нашли, либо отреагировать на ResetEvents/WaitObjects по потокам.
Обычно вызывать рабочие элементы в потоке пользовательского интерфейса — это плохо, если только это не является частью работы пользовательского интерфейса (т.е. обновлением контрольного контента или чего-то еще), и в этом случае Control.BeginInvoke() будет достаточным.
Я привел пример использования System.Windows.Threading.Dispatcher в Windows Form в ответе на вопрос «Параллельное программирование с использованием TPL на WinForms», поскольку предыдущий ответ на ваш вопрос:
Если вы уверены, что находитесь в потоке пользовательского интерфейса (например, в кнопке button.Click handler), Dispatcher.CurrentDispatcher предоставляет диспетчер потоков пользовательского интерфейса, который вы можете использовать для отправки из фонового потока в поток пользовательского интерфейса, как обычно.
либо вводит в заблуждение, либо вводит в заблуждение, либо не имеет конкретного контекста использования:
- button.Click обработчик не гарантирует, что будет в потоке пользовательского интерфейса;
Если вы не используете поток пользовательского интерфейса, по-прежнему можно использовать несовпадение нити пользовательского интерфейса формы WinForms
Можно получить диспетчера потока WinForm UI:
в любом обработчике событий нажатия кнопки или в другом месте (в конструкторе форм)
И затем используйте его для выполнения в пользовательском интерфейсе из других потоков, более подробно см. ниже в мой ответ: