System windows threading dispatcher invoke

Dispatcher Класс

Определение

Предоставляет службы для управления очередью рабочих элементов для потока. Provides services for managing the queue of work items for a thread.

Примеры

В следующем примере показано, как поместить операцию в Dispatcher . The following example shows how to place an operation onto a Dispatcher. Полный исходный код этого примера см. в разделе Пример однопотокового приложения с Long-Runningным вычислением. 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.

Затем BeginInvoke(DispatcherPriority, Delegate) вызывается метод. Next, BeginInvoke(DispatcherPriority, Delegate) is called. Этот вызов BeginInvoke(DispatcherPriority, Delegate) принимает два параметра: приоритет, который имеет значение DispatcherPriority.Normal , и обратный вызов, который передается через экземпляр делегата NextPrimeDelegate . 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 .

Комментарии

DispatcherПоддерживает приоритетную очередь рабочих элементов для конкретного потока. The Dispatcher maintains a prioritized queue of work items for a specific thread.

Когда объект создается Dispatcher в потоке, он становится единственным Dispatcher , который может быть связан с потоком, даже если работа завершается Dispatcher . 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.

Если попытаться получить CurrentDispatcher для текущего потока, а Dispatcher не связать с потоком, Dispatcher будет создан объект. 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. А Dispatcher также создается при создании DispatcherObject . A Dispatcher is also created when you create a DispatcherObject. При создании в Dispatcher фоновом потоке обязательно завершите работу диспетчера перед выходом из потока. If you create a Dispatcher on a background thread, be sure to shut down the dispatcher before exiting the thread.

Если работа выключена Dispatcher , ее невозможно перезапустить. If a Dispatcher is shut down, it cannot be restarted.

В WPF доступ к DispatcherObject может осуществляться только тем, что Dispatcher он связан с. In WPF, a DispatcherObject can only be accessed by the Dispatcher it is associated with. Например, фоновый поток не может обновить содержимое объекта Button , связанного с параметром Dispatcher в ПОТОКЕ пользовательского интерфейса. For example, a background thread cannot update the contents of a Button that is associated with the Dispatcher on the UI thread. Чтобы фоновый поток мог получить доступ к Content свойству Button , фоновый поток должен делегировать работу, Dispatcher связанную с потоком пользовательского интерфейса. 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. Это достигается с помощью Invoke или BeginInvoke . This is accomplished by using either Invoke or BeginInvoke. Invoke является синхронным и BeginInvoke является асинхронным. Invoke is synchronous and BeginInvoke is asynchronous. Операция добавляется в очередь в Dispatcher указанной DispatcherPriority . The operation is added to the queue of the Dispatcher at the specified DispatcherPriority.

Если BeginInvoke метод вызывается для объекта Dispatcher , который завершил работу, свойство Status возвращаемого значения DispatcherOperation устанавливается в значение Aborted . If BeginInvoke is called on a Dispatcher that has shut down, the status property of the returned DispatcherOperation is set to Aborted.

Все методы в Dispatcher , за исключением DisableProcessing , являются свободными потоками. All of the methods on Dispatcher, with the exception of DisableProcessing, are free-threaded.

Читайте также:  Почему не запускается idle python mac os

Объекты, производные от, DispatcherObject имеют сходство потоков. Objects that derive from DispatcherObject have thread affinity.

Объекты, производные от Freezable , являются свободными потоками, когда они заморожены. Objects that derive from Freezable are free-threaded when they are frozen. Дополнительные сведения см. в разделе Общие сведения об объектах класса Freezable. For more information, see Freezable Objects Overview.

Свойства

Возвращает Dispatcher для выполняющегося в данный момент потока и создает новый объект Dispatcher, если с потоком еще не связан диспетчер. Gets the Dispatcher for the thread currently executing and creates a new Dispatcher if one is not already associated with the thread.

Определяет, завершил ли объект Dispatcher процесс остановки. Determines whether the Dispatcher has finished shutting down.

Определяет, находится ли объект Dispatcher в процессе остановки. Determines whether the Dispatcher is shutting down.

Возвращает коллекцию ловушек, предоставляющих дополнительную информацию о Dispatcher. Gets the collection of hooks that provide additional event information about the Dispatcher.

Возвращает поток, с которым связан данный Dispatcher. Gets the thread this Dispatcher is associated with.

Методы

Выполняет указанный делегат асинхронно, с заданными приоритетом и аргументами, в потоке, в котором был создан объект Dispatcher. Executes the specified delegate asynchronously with the specified arguments, at the specified priority, on the thread that the Dispatcher was created on.

Выполняет указанный делегат асинхронно с указанными аргументами в потоке, в котором был создан объект Dispatcher. Executes the specified delegate asynchronously with the specified arguments on the thread that the Dispatcher was created on.

Выполняет указанный делегат асинхронно, с заданным приоритетом, в потоке, с которым связан Dispatcher. Executes the specified delegate asynchronously at the specified priority on the thread the Dispatcher is associated with.

Выполняет указанный делегат асинхронно, с заданными приоритетом и аргументом, в потоке, с которым связан Dispatcher. Executes the specified delegate asynchronously at the specified priority and with the specified argument on the thread the Dispatcher is associated with.

Выполняет указанный делегат асинхронно, с заданными приоритетом и массивом аргументов, в потоке, с которым связан Dispatcher. Executes the specified delegate asynchronously at the specified priority and with the specified array of arguments on the thread the Dispatcher is associated with.

Инициализирует асинхронную остановку Dispatcher. Initiates shutdown of the Dispatcher asynchronously.

Определяет, связан ли вызывающий поток с данным Dispatcher. Determines whether the calling thread is the thread associated with this Dispatcher.

Отменяет обработку очереди Dispatcher. Disables processing of the Dispatcher queue.

Определяет, равен ли указанный объект текущему объекту. Determines whether the specified object is equal to the current object.

(Унаследовано от Object) ExitAllFrames()

Запрашивает выход для всех фреймов, включая вложенные. Requests that all frames exit, including nested frames.

Возвращает Dispatcher для заданного потока. Gets the Dispatcher for the specified thread.

Служит хэш-функцией по умолчанию. Serves as the default hash function.

(Унаследовано от Object) GetType()

Возвращает объект Type для текущего экземпляра. Gets the Type of the current instance.

(Унаследовано от Object) Invoke(Action)

Выполняет заданный объект Action синхронно в потоке, с которым связан Dispatcher. Executes the specified Action synchronously on the thread the Dispatcher is associated with.

Выполняет указанный объект Action синхронно с заданным приоритетом в потоке, с которым связан Dispatcher. Executes the specified Action synchronously at the specified priority on the thread the Dispatcher is associated with.

Выполняет указанный объект Action синхронно с заданным приоритетом в потоке, с которым связан Dispatcher. Executes the specified Action synchronously at the specified priority on the thread the Dispatcher is associated with.

Читайте также:  Asus boot setting windows 10 64 bit

Выполняет указанный объект Action синхронно с заданным приоритетом в потоке, с которым связан Dispatcher. Executes the specified Action synchronously at the specified priority on the thread the Dispatcher is associated with.

Выполняет указанный делегат синхронно, с заданными приоритетом и аргументами, в потоке, с которым связан Dispatcher. Executes the specified delegate at the specified priority with the specified arguments synchronously on the thread the Dispatcher is associated with.

Выполняет указанный делегат синхронно с заданными аргументами в потоке, с которым связан объект Dispatcher. Executes the specified delegate with the specified arguments synchronously on the thread the Dispatcher is associated with.

Выполняет указанный делегат в течение заданного промежутка времени, синхронно, с заданными приоритетом и аргументами, в потоке, с которым связан Dispatcher. 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.

Выполняет указанный делегат в течение заданного промежутка времени, синхронно, с заданными приоритетом и аргументами, в потоке, с которым связан Dispatcher. 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.

Выполняет указанный делегат в синхронном режиме по заданному приоритету в потоке, Dispatcher с которым связан объект. Executes the specified delegate synchronously at the specified priority on the thread that the Dispatcher is associated with.

Выполняет указанный делегат синхронно, с заданными приоритетом и аргументом, в потоке, с которым связан Dispatcher. Executes the specified delegate at the specified priority with the specified argument synchronously on the thread the Dispatcher is associated with.

Выполняет указанный делегат синхронно, с заданными приоритетом и аргументами, в потоке, с которым связан Dispatcher. Executes the specified delegate at the specified priority with the specified arguments synchronously on the thread the Dispatcher is associated with.

Выполняет указанный делегат асинхронно, с заданными приоритетом и значением таймаута, в потоке, в котором был создан объект Dispatcher. Executes the specified delegate synchronously at the specified priority and with the specified time-out value on the thread the Dispatcher was created.

Выполняет указанный делегат синхронно, с заданными приоритетом и аргументом, в потоке, с которым связан Dispatcher. Executes the specified delegate at the specified priority with the specified argument synchronously on the thread the Dispatcher is associated with.

Выполняет указанный делегат синхронно, с заданными приоритетом и аргументами, в потоке, с которым связан Dispatcher. Executes the specified delegate at the specified priority with the specified arguments synchronously on the thread the Dispatcher is associated with.

Выполняет заданный объект Action асинхронно в потоке, с которым связан Dispatcher. Executes the specified Action asynchronously on the thread the Dispatcher is associated with.

Выполняет указанный объект Action асинхронно с заданным приоритетом в потоке, с которым связан Dispatcher. Executes the specified Action asynchronously at the specified priority on the thread the Dispatcher is associated with.

Выполняет указанный объект Action асинхронно с заданным приоритетом в потоке, с которым связан Dispatcher. Executes the specified Action asynchronously at the specified priority on the thread the Dispatcher is associated with.

Инициирует синхронный процесс остановки Dispatcher. Initiates the shutdown process of the Dispatcher synchronously.

Создает неполную копию текущего объекта Object. Creates a shallow copy of the current Object.

Читайте также:  Сетевой адаптер broadcom netlink tm gigabit ethernet драйвер windows 10

(Унаследовано от Object) PushFrame(DispatcherFrame)

Входит в цикл выполнения. Enters an execute loop.

Помещает главный фрейм выполнения в очередь событий Dispatcher. Pushes the main execution frame on the event queue of the Dispatcher.

Возвращает строку, представляющую текущий объект. Returns a string that represents the current object.

(Унаследовано от Object) ValidatePriority(DispatcherPriority, String)

Определяет, является ли DispatcherPriority допустимым приоритетом. Determines whether the specified DispatcherPriority is a valid priority.

Определяет, имеет ли вызывающий поток доступ к этому Dispatcher. Determines whether the calling thread has access to this Dispatcher.

Создает объект типа awaitable, который асинхронно направляет элемент управления обратно текущему диспетчеру и предоставляет диспетчеру возможность обработки других событий. Creates an awaitable object that asynchronously yields control back to the current dispatcher and provides an opportunity for the dispatcher to process other events.

Создает объект типа awaitable, который асинхронно направляет элемент управления обратно текущему диспетчеру и предоставляет диспетчеру возможность обработки других событий. 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.

События

Происходит после остановки Dispatcher. Occurs when the Dispatcher finishes shutting down.

Происходит, когда начинается процесс остановки Dispatcher. Occurs when the Dispatcher begins to shut down.

Происходит, когда выбрасывается и никаким кодом не перехватывается исключение потока при выполнении делегата с помощью Invoke или BeginInvoke. Occurs when a thread exception is thrown and uncaught during execution of a delegate by way of Invoke or BeginInvoke.

Происходит, когда выбрасывается и никаким кодом не перехватывается исключение потока при выполнении делегата с помощью Invoke или 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.

Методы расширения

Выполняет указанный делегат асинхронно с обычным приоритетом, в потоке, в котором был создан заданный объект Dispatcher. Executes the specified delegate asynchronously with normal priority on the thread that the specified Dispatcher was created on.

Выполняет указанный делегат асинхронно с заданным приоритетом, в потоке, в котором был создан заданный объект Dispatcher. Executes the specified delegate asynchronously with the specified priority on the thread that the specified Dispatcher was created on.

Выполняет указанный делегат синхронно с обычным приоритетом, в потоке, в котором был создан заданный объект Dispatcher. Executes the specified delegate synchronously with normal priority on the thread that the specified Dispatcher was created on.

Выполняет указанный делегат синхронно, в потоке, в котором был создан объект Dispatcher, и прекращает выполнение по истечении указанного времени ожидания. Executes the specified delegate synchronously on the thread that the specified Dispatcher was created on, and stops execution after the specified time-out period.

Выполняет указанный делегат синхронно, с заданным приоритетом, в потоке, в котором был создан объект Dispatcher, и прекращает выполнение по истечении указанного времени ожидания. 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.

Выполняет указанный делегат синхронно с заданным приоритетом, в потоке, в котором был создан заданный объект Dispatcher. Executes the specified delegate synchronously with the specified priority on the thread that the specified Dispatcher was created on.

Оцените статью