Using system windows threading

System. Threading. Tasks Пространство имен

Предоставляет типы, которые упрощают работу по написанию параллельного и асинхронного кода. Provides types that simplify the work of writing concurrent and asynchronous code. Основные типы: Task, представляющий асинхронную операцию, которую можно ожидать и отменить, и Task , представляющий собой задачу, которая может вернуть значение. The main types are Task which represents an asynchronous operation that can be waited on and cancelled, and Task , which is a task that can return a value. Класс TaskFactory предоставляет статические методы для создания задач, а класс TaskScheduler предоставляет инфраструктуру планирования потоков по умолчанию. The TaskFactory class provides static methods for creating and starting tasks, and the TaskScheduler class provides the default thread scheduling infrastructure.

Классы

Предоставляет планировщики задачи, которые координируются для выполнения задач, обеспечивая то, что параллельные задачи могут выполняться одновременно, а эксклюзивные задачи — нет. Provides task schedulers that coordinate to execute tasks while ensuring that concurrent tasks may run concurrently and exclusive tasks never do.

Предоставляет поддержку параллельных циклов и областей. Provides support for parallel loops and regions.

Позволяет итерациям параллельных циклов взаимодействовать с другими итерациями. Enables iterations of parallel loops to interact with other iterations. Экземпляр этого класса предоставляется каждому циклу классом Parallel; невозможно создавать экземпляры в коде. An instance of this class is provided by the Parallel class to each loop; you can not create instances in your code.

Хранит параметры, настраивающие работу методов класса Parallel. Stores options that configure the operation of methods on the Parallel class.

Представляет асинхронную операцию. Represents an asynchronous operation.

Представляет асинхронную операцию, которая может вернуть значение. Represents an asynchronous operation that can return a value.

Предоставляет набор статических методов для настройки задач, связанных с асинхронными перечислимыми и высвобождаемыми объектами. Provides a set of static methods for configuring task-related behaviors on asynchronous enumerables and disposables.

Представляет исключение, используемое для передачи отмены задачи. Represents an exception used to communicate task cancellation.

Представляет сторону производителя задач Task, не привязанных к делегату и предоставляющих доступ к потребительской стороне через свойство Task. Represents the producer side of a Task unbound to a delegate, providing access to the consumer side through the Task property.

Предоставляет набор статических методов (Shared в Visual Basic) для работы с определенными типами экземпляров Task. Provides a set of static (Shared in Visual Basic) methods for working with specific kinds of Task instances.

Предоставляет поддержку создания и планирования объектов Task. Provides support for creating and scheduling Task objects.

Представляет объект, обрабатывающий низкоуровневую постановку задач в очередь на потоки. Represents an object that handles the low-level work of queuing tasks onto threads.

Представляет исключение, используемое для передачи недопустимой операции планировщиком TaskScheduler. Represents an exception used to communicate an invalid operation by a TaskScheduler.

Предоставляет данные для события, создаваемого, если происходит непредвиденное исключение задачи с ошибкой Task. Provides data for the event that is raised when a faulted Task’s exception goes unobserved.

Структуры

Предоставляет состояние выполнения цикла Parallel. Provides completion status on the execution of a Parallel loop.

Предоставляет ожидаемый результат асинхронной операции. Provides an awaitable result of an asynchronous operation.

Перечисления

Задает флаги, которые управляют необязательным поведением создания и выполнения задач. Specifies flags that control optional behavior for the creation and execution of tasks.

Представляет текущий этап жизненного цикла задачи Task. Represents the current stage in the lifecycle of a Task.

System. Windows. Threading Пространство имен

Содержит типы для поддержки системы работы с потоками Windows Presentation Foundation (WPF). Contains types to support the Windows Presentation Foundation (WPF) threading system.

Классы

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

Предоставляет данные для событий, связанных с Dispatcher. Provides event data for Dispatcher related events.

Предоставляет набор методов static , которые расширяют класс Dispatcher. Provides a set of static methods that extend the Dispatcher class.

Представляет цикл выполнения в Dispatcher. Represents an execution loop in the Dispatcher.

Предоставляет данные для событий DispatcherHooks. Provides event data for DispatcherHooks events.

Предоставляет дополнительные сведения о работе Dispatcher. Provides additional event information about Dispatcher processing.

Представляет объект, связанный с объектом Dispatcher. Represents an object that is associated with a Dispatcher.

Представляет объект, используемый для взаимодействия с операцией, помещенной в очередь объекта Dispatcher. Represents an object that is used to interact with an operation that has been posted to the Dispatcher queue.

Представляет объект, используемый для взаимодействия с операцией, помещенной в очередь Dispatcher, и содержит Task . Represents an object that is used to interact with an operation that has been posted to the Dispatcher queue and contains a Task .

Предоставляет контекст синхронизации для Windows Presentation Foundation (WPF). Provides a synchronization context for Windows Presentation Foundation (WPF).

Таймер, интегрированный в очередь Dispatcher, обрабатываемый с заданным интервалом времени и заданным приоритетом. A timer that is integrated into the Dispatcher queue which is processed at a specified interval of time and at a specified priority.

Читайте также:  Не могу запустить линукс с биоса

Предоставляет данные для события DispatcherUnhandledException. Provides data for the DispatcherUnhandledException event.

Предоставляет набор методов static , которые расширяют класс Task. Provides a set of static methods that extend the Task class.

Структуры

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

Предоставляет объект, который ожидает завершения асинхронной задачи. Represents an object that waits for the completion of an asynchronous task.

Представляет объект Dispatcher, когда он отличен, и предоставляет средства для его повторного включения. Represents the Dispatcher when it is in a disable state and provides a means to re-enable dispatcher processing.

Перечисления

Описывает возможные значения состояния DispatcherOperation. Describes the possible values for the status of a DispatcherOperation.

Описывает приоритеты, с которыми могут вызываться операции посредством Dispatcher. Describes the priorities at which operations can be invoked by way of the Dispatcher.

Делегаты

Представляет метод обработки событий, связанных с DispatcherHooks. Represents the method that will handle DispatcherHooks related events.

Представляет делегат для использования в операциях диспетчера. Represents a delegate to use for dispatcher operations.

Представляет метод обработки события UnhandledException. Represents the method that will handle the UnhandledException event.

Представляет метод обработки события UnhandledExceptionFilter. Represents the method that will handle the UnhandledExceptionFilter event.

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.

Объекты, производные от, 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.

Читайте также:  Installing printer in linux

Свойства

Возвращает 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.

Выполняет указанный объект 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.

Читайте также:  Папка пользователя windows 10 занимает много места

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

(Унаследовано от 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.

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