System windows threading dll

Dispatcher Timer Класс

Определение

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

Примеры

В следующем примере создается объект DispatcherTimer , который обновляет содержимое объекта Label и вызывает InvalidateRequerySuggested метод для CommandManager . The following example creates a DispatcherTimer that updates the contents of a Label and calls the InvalidateRequerySuggested method on the CommandManager.

DispatcherTimerСоздается объект с именем dispatcherTimer . A DispatcherTimer object named dispatcherTimer is created. Обработчик событий dispatcherTimer_Tick добавляется к Tick событию dispatcherTimer . The event handler dispatcherTimer_Tick is added to the Tick event of dispatcherTimer . Значение Interval задается равным 1 секунде с помощью TimeSpan объекта и запускается таймер. The Interval is set to 1 second using a TimeSpan object, and the timer is started.

TickОбработчик событий обновляет объект Label , отображающий текущую секунду, и вызывает метод InvalidateRequerySuggested в CommandManager . The Tick event handler updates a Label that displays the current second, and it calls InvalidateRequerySuggested on the CommandManager.

Комментарии

DispatcherTimerВычисляется повторно в верхней части каждого Dispatcher цикла. The DispatcherTimer is reevaluated at the top of every Dispatcher loop.

Таймеры не гарантированно выполняются в точности при наступлении интервала времени, но они гарантированно не будут выполняться до наступления интервала времени. Timers are not guaranteed to execute exactly when the time interval occurs, but they are guaranteed to not execute before the time interval occurs. Это связано с тем, что DispatcherTimer операции помещаются в Dispatcher очередь, как и другие операции. This is because DispatcherTimer operations are placed on the Dispatcher queue like other operations. Когда DispatcherTimer операция выполняется, зависит от других заданий в очереди и их приоритетов. When the DispatcherTimer operation executes is dependent on the other jobs in the queue and their priorities.

Если System.Timers.Timer используется в приложении WPF, стоит отметить, что объект System.Timers.Timer выполняется в потоке, отличном от потока пользовательского интерфейса. If a System.Timers.Timer is used in a WPF application, it is worth noting that the System.Timers.Timer runs on a different thread than the user interface (UI) thread. Чтобы получить доступ к объектам в потоке пользовательского интерфейса, необходимо опубликовать операцию в Dispatcher потоке пользовательского интерфейса с помощью Invoke или BeginInvoke . In order to access objects on the user interface (UI) thread, it is necessary to post the operation onto the Dispatcher of the user interface (UI) thread using Invoke or BeginInvoke. Причины использования, в отличие от, — выполняются в DispatcherTimer System.Timers.Timer DispatcherTimer том же потоке, что Dispatcher и, и DispatcherPriority могут быть установлены в DispatcherTimer . Reasons for using a DispatcherTimer as opposed to a System.Timers.Timer are that the DispatcherTimer runs on the same thread as the Dispatcher and a DispatcherPriority can be set on the DispatcherTimer.

DispatcherTimerОбъект будет поддерживать активность объекта всякий раз, когда методы объекта привязаны к таймеру. A DispatcherTimer will keep an object alive whenever the object’s methods are bound to the timer.

Конструкторы

Инициализирует новый экземпляр класса DispatcherTimer. Initializes a new instance of the DispatcherTimer class.

Инициализирует новый экземпляр класса DispatcherTimer, обрабатывающий события таймера с заданным приоритетом. Initializes a new instance of the DispatcherTimer class which processes timer events at the specified priority.

Инициализирует новый экземпляр класса DispatcherTimer, который выполняется с заданным приоритетом заданным объектом Dispatcher. Initializes a new instance of the DispatcherTimer class which runs on the specified Dispatcher at the specified priority.

Инициализирует новый экземпляр класса DispatcherTimer, устанавливая для него заданные интервал, приоритет, обработчик событий и объект Dispatcher. Initializes a new instance of the DispatcherTimer class which uses the specified time interval, priority, event handler, and Dispatcher.

Свойства

Возвращает объект Dispatcher, связанный с этим объектом DispatcherTimer. Gets the Dispatcher associated with this DispatcherTimer.

Возвращает или задает период времени между тактами таймера. Gets or sets the period of time between timer ticks.

Возвращает или задает значение, указывающее, работает ли таймер. Gets or sets a value that indicates whether the timer is running.

Получает или задает определенные пользователем данные объекта. Gets or sets a user-defined data object.

Методы

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

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

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

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

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

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

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

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

Читайте также:  Tp link archer t2u plus драйвера linux

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

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

События

Происходит по истечении интервала таймера. Occurs when the timer interval has elapsed.

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.

Свойства

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

Читайте также:  Redis gui client linux

Методы

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

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

Читайте также:  Program has been detected windows has been

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

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