System windows forms control invoke

Control. Invoke Метод

Определение

Выполняет делегат в том потоке, которому принадлежит базовый дескриптор окна элемента управления. Executes a delegate on the thread that owns the control’s underlying window handle.

Перегрузки

Выполняет указанный делегат в том потоке, которому принадлежит базовый дескриптор окна элемента управления. Executes the specified delegate on the thread that owns the control’s underlying window handle.

Выполняет указанный делегат в том потоке, которому принадлежит основной дескриптор окна элемента управления, с указанным списком аргументов. Executes the specified delegate, on the thread that owns the control’s underlying window handle, with the specified list of arguments.

Invoke(Delegate)

Выполняет указанный делегат в том потоке, которому принадлежит базовый дескриптор окна элемента управления. Executes the specified delegate on the thread that owns the control’s underlying window handle.

Параметры

Делегат, содержащий метод, который требуется вызывать в контексте потока элемента управления. A delegate that contains a method to be called in the control’s thread context.

Возвращаемое значение

Значение, возвращаемое вызываемым делегатом, или значение null , если делегат не возвращает никакого значения. The return value from the delegate being invoked, or null if the delegate has no return value.

Примеры

В следующем примере кода показаны элементы управления, которые содержат делегат. The following code example shows controls that contain a delegate. Делегат инкапсулирует метод, который добавляет элементы в список, и этот метод выполняется в потоке, владеющем базовым маркером формы. The delegate encapsulates a method that adds items to the list box, and this method is executed on the thread that owns the underlying handle of the form. Когда пользователь нажимает кнопку, Invoke запускает делегат. When the user clicks on the button, Invoke runs the delegate.

Комментарии

Делегаты похожи на указатели функций в языках C или C++. Delegates are similar to function pointers in C or C++ languages. Делегаты инкапсулируют ссылку на метод внутри объекта делегата. Delegates encapsulate a reference to a method inside a delegate object. Затем объект делегата может быть передан в код, вызывающий упоминаемый метод, а вызываемый метод может быть неизвестным во время компиляции. The delegate object can then be passed to code that calls the referenced method, and the method to be invoked can be unknown at compile time. В отличие от указателей функций в C или C++ делегаты являются объектно-ориентированными, строго типизированными и более безопасными. Unlike function pointers in C or C++, delegates are object-oriented, type-safe, and more secure.

InvokeМетод выполняет поиск по родительской цепочке элемента управления до тех пор, пока не обнаружит элемент управления или форму, которые имеют обработчик окна, если его базовый маркер окна текущего элемента управления еще не существует. The Invoke method searches up the control’s parent chain until it finds a control or form that has a window handle if the current control’s underlying window handle does not exist yet. Если не удается найти соответствующий обработчик, Invoke метод вызовет исключение. If no appropriate handle can be found, the Invoke method will throw an exception. Исключения, возникающие во время вызова, передаются обратно вызывающему объекту. Exceptions that are raised during the call will be propagated back to the caller.

Помимо InvokeRequired свойства, существует четыре метода элемента управления, которые являются потокобезопасными: Invoke ,, и, BeginInvoke EndInvoke CreateGraphics Если уже был создан обработчик для элемента управления. In addition to the InvokeRequired property, there are four methods on a control that are thread safe: Invoke, BeginInvoke, EndInvoke, and CreateGraphics if the handle for the control has already been created. Вызов CreateGraphics перед созданием маркера элемента управления в фоновом потоке может привести к недопустимым перекрестным вызовам потоков. Calling CreateGraphics before the control’s handle has been created on a background thread can cause illegal cross thread calls. Для всех остальных вызовов методов следует использовать один из методов Invoke для маршалирования вызова в поток элемента управления. For all other method calls, you should use one of the invoke methods to marshal the call to the control’s thread.

Делегат может быть экземпляром EventHandler , в этом случае параметр sender будет содержать этот элемент управления, а параметр события будет содержать EventArgs.Empty . The delegate can be an instance of EventHandler, in which case the sender parameter will contain this control, and the event parameter will contain EventArgs.Empty. Делегат также может быть экземпляром MethodInvoker или любым другим делегатом, принимающим список параметров void. The delegate can also be an instance of MethodInvoker, or any other delegate that takes a void parameter list. Вызов EventHandler MethodInvoker делегата или будет выполняться быстрее, чем вызов другого типа делегата. A call to an EventHandler or MethodInvoker delegate will be faster than a call to another type of delegate.

Читайте также:  Checkpoint snx windows 10

Исключение может быть вызвано, если поток, который должен обработать сообщение, больше не активен. An exception might be thrown if the thread that should process the message is no longer active.

Control. Begin Invoke Метод

Определение

Выполняет делегат асинхронно в потоке, в котором был создан базовый дескриптор элемента управления. Executes a delegate asynchronously on the thread that the control’s underlying handle was created on.

Перегрузки

Выполняет указанный делегат асинхронно в потоке, в котором был создан базовый дескриптор элемента управления. Executes the specified delegate asynchronously on the thread that the control’s underlying handle was created on.

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

BeginInvoke(Delegate)

Выполняет указанный делегат асинхронно в потоке, в котором был создан базовый дескриптор элемента управления. Executes the specified delegate asynchronously on the thread that the control’s underlying handle was created on.

Параметры

Делегат метода, который не принимает параметров. A delegate to a method that takes no parameters.

Возвращаемое значение

Объект IAsyncResult, который представляет результат выполнения операции BeginInvoke(Delegate). An IAsyncResult that represents the result of the BeginInvoke(Delegate) operation.

Исключения

Соответствующий дескриптор окна не обнаружен. No appropriate window handle can be found.

Примеры

В следующем примере кода демонстрируется использование BeginInvoke метода. The following code example demonstrates a use of the BeginInvoke method.

Комментарии

Делегат вызывается асинхронно, и этот метод немедленно возвращает значение. The delegate is called asynchronously, and this method returns immediately. Этот метод можно вызвать из любого потока, даже из потока, владеющего маркером элемента управления. You can call this method from any thread, even the thread that owns the control’s handle. Если маркер элемента управления еще не существует, этот метод выполняет поиск по родительской цепочке элемента управления до тех пор, пока не обнаружит элемент управления или форму, у которых есть обработчик окна. If the control’s handle does not exist yet, this method searches up the control’s parent chain until it finds a control or form that does have a window handle. Если соответствующий маркер не найден, BeginInvoke создает исключение. If no appropriate handle can be found, BeginInvoke will throw an exception. Исключения в методе делегата считаются неперехваченными и отправляются в обработчик исключений неперехваченного приложения. Exceptions within the delegate method are considered untrapped and will be sent to the application’s untrapped exception handler.

Вы можете вызвать метод, EndInvoke чтобы получить возвращаемое значение от делегата, если необходимых, но это не является обязательным. You can call EndInvoke to retrieve the return value from the delegate, if neccesary, but this is not required. EndInvoke блокируется до тех пор, пока не будет получено возвращаемое значение. EndInvoke will block until the return value can be retrieved.

Большинство методов элемента управления могут вызываться только из потока, в котором был создан элемент управления. Most methods on a control can only be called from the thread where the control was created. Помимо InvokeRequired свойства, существует четыре метода элемента управления, которые являются потокобезопасными: Invoke ,, и, BeginInvoke EndInvoke CreateGraphics Если уже был создан обработчик для элемента управления. In addition to the InvokeRequired property, there are four methods on a control that are thread safe: Invoke, BeginInvoke, EndInvoke, and CreateGraphics if the handle for the control has already been created. Вызов CreateGraphics перед созданием маркера элемента управления в фоновом потоке может привести к недопустимым перекрестным вызовам потоков. Calling CreateGraphics before the control’s handle has been created on a background thread can cause illegal cross thread calls. Для всех остальных вызовов методов следует использовать один из методов Invoke для маршалирования вызова в поток элемента управления. For all other method calls, you should use one of the invoke methods to marshal the call to the control’s thread. Методы Invoke всегда вызывают свои обратные вызовы в потоке элемента управления. The invoke methods always invoke their callbacks on the control’s thread.

Читайте также:  Как почистить компьютер полностью без переустановки windows

Исключение может быть вызвано, если поток, который должен обработать сообщение, больше не активен. An exception might be thrown if the thread that should process the message is no longer active.

Control. Invoke Method

Definition

Executes a delegate on the thread that owns the control’s underlying window handle.

Overloads

Executes the specified delegate on the thread that owns the control’s underlying window handle.

Executes the specified delegate, on the thread that owns the control’s underlying window handle, with the specified list of arguments.

Invoke(Delegate)

Executes the specified delegate on the thread that owns the control’s underlying window handle.

Parameters

A delegate that contains a method to be called in the control’s thread context.

Returns

The return value from the delegate being invoked, or null if the delegate has no return value.

Examples

The following code example shows controls that contain a delegate. The delegate encapsulates a method that adds items to the list box, and this method is executed on the thread that owns the underlying handle of the form. When the user clicks on the button, Invoke runs the delegate.

Remarks

Delegates are similar to function pointers in C or C++ languages. Delegates encapsulate a reference to a method inside a delegate object. The delegate object can then be passed to code that calls the referenced method, and the method to be invoked can be unknown at compile time. Unlike function pointers in C or C++, delegates are object-oriented, type-safe, and more secure.

The Invoke method searches up the control’s parent chain until it finds a control or form that has a window handle if the current control’s underlying window handle does not exist yet. If no appropriate handle can be found, the Invoke method will throw an exception. Exceptions that are raised during the call will be propagated back to the caller.

In addition to the InvokeRequired property, there are four methods on a control that are thread safe: Invoke, BeginInvoke, EndInvoke, and CreateGraphics if the handle for the control has already been created. Calling CreateGraphics before the control’s handle has been created on a background thread can cause illegal cross thread calls. For all other method calls, you should use one of the invoke methods to marshal the call to the control’s thread.

The delegate can be an instance of EventHandler, in which case the sender parameter will contain this control, and the event parameter will contain EventArgs.Empty. The delegate can also be an instance of MethodInvoker, or any other delegate that takes a void parameter list. A call to an EventHandler or MethodInvoker delegate will be faster than a call to another type of delegate.

An exception might be thrown if the thread that should process the message is no longer active.

Control. Invoke Required Свойство

Определение

Возвращает значение, указывающее, следует ли вызывающему оператору обращаться к методу invoke во время вызовов метода из элемента управления, так как вызывающий оператор находится не в том потоке, в котором был создан элемент управления. Gets a value indicating whether the caller must call an invoke method when making method calls to the control because the caller is on a different thread than the one the control was created on.

Значение свойства

Значение true , если свойство Handle элемента управления было создано не в вызывающем потоке, а в другом (показывает, что необходимо вызвать элемент управления через метод invoke); в противном случае — значение false . true if the control’s Handle was created on a different thread than the calling thread (indicating that you must make calls to the control through an invoke method); otherwise, false .

Реализации

Комментарии

Элементы управления в Windows Forms привязаны к определенному потоку и не являются потокобезопасными. Controls in Windows Forms are bound to a specific thread and are not thread safe. Поэтому при вызове метода элемента управления из другого потока необходимо использовать один из методов Invoke элемента управления для маршалирования вызова в нужный поток. Therefore, if you are calling a control’s method from a different thread, you must use one of the control’s invoke methods to marshal the call to the proper thread. Это свойство можно использовать для определения необходимости вызова метода Invoke, который может быть полезен, если неизвестно, какой поток владеет элементом управления. This property can be used to determine if you must call an invoke method, which can be useful if you do not know what thread owns a control.

Читайте также:  Если ноутбук закрыть загрузка продолжится windows 10

Помимо InvokeRequired свойства, в элементе управления есть четыре метода, которые являются потокобезопасными для вызова: Invoke , BeginInvoke EndInvoke и CreateGraphics Если маркер для элемента управления уже был создан. In addition to the InvokeRequired property, there are four methods on a control that are thread safe to call: Invoke,BeginInvoke, EndInvoke and CreateGraphics if the handle for the control has already been created. Вызов CreateGraphics перед созданием маркера элемента управления в фоновом потоке может привести к недопустимым перекрестным вызовам потоков. Calling CreateGraphics before the control’s handle has been created on a background thread can cause illegal cross thread calls. Для всех остальных вызовов методов следует использовать один из этих методов Invoke при вызове из другого потока. For all other method calls, you should use one of these invoke methods when calling from a different thread.

Если маркер элемента управления еще не существует, InvokeRequired выполняет поиск по родительской цепочке элемента управления до тех пор, пока не обнаружит элемент управления или форму, у которых есть обработчик окна. If the control’s handle does not yet exist, InvokeRequired searches up the control’s parent chain until it finds a control or form that does have a window handle. Если соответствующий обработчик не найден, InvokeRequired метод возвращает значение false . If no appropriate handle can be found, the InvokeRequired method returns false .

Это означает, что InvokeRequired может возвратить, false Если Invoke не требуется (вызов происходит в том же потоке) или если элемент управления был создан в другом потоке, но его обработчик еще не был создан. This means that InvokeRequired can return false if Invoke is not required (the call occurs on the same thread), or if the control was created on a different thread but the control’s handle has not yet been created.

В случае, когда маркер элемента управления еще не был создан, не следует просто вызывать свойства, методы или события в элементе управления. In the case where the control’s handle has not yet been created, you should not simply call properties, methods, or events on the control. Это может привести к тому, что маркер элемента управления будет создан в фоновом потоке, изолируя элемент управления в потоке без конвейера сообщений и не делая приложение нестабильным. This might cause the control’s handle to be created on the background thread, isolating the control on a thread without a message pump and making the application unstable.

Для защиты в этом случае можно также проверить значение IsHandleCreated при InvokeRequired возврате false в фоновом потоке. You can protect against this case by also checking the value of IsHandleCreated when InvokeRequired returns false on a background thread. Если управляющий элемент еще не создан, необходимо дождаться его создания до вызова метода Invoke или BeginInvoke . If the control handle has not yet been created, you must wait until it has been created before calling Invoke or BeginInvoke. Как правило, это происходит только в том случае, если фоновый поток создается в конструкторе основной формы для приложения (как в Application.Run(new MainForm()) , до отображения или вызова формы) Application.Run . Typically, this happens only if a background thread is created in the constructor of the primary form for the application (as in Application.Run(new MainForm()) , before the form has been shown or Application.Run has been called.

Одним из решений является ожидание создания маркера формы перед запуском фонового потока. One solution is to wait until the form’s handle has been created before starting the background thread. Либо принудительное создание обработчика путем вызова Handle свойства, либо подождите, пока Load событие не запустит фоновый процесс. Either force handle creation by calling the Handle property, or wait until the Load event to start the background process.

Еще лучшим решением является использование SynchronizationContext возвращаемого объекта, SynchronizationContext а не элемента управления для маршалинга между потоками. An even better solution is to use the SynchronizationContext returned by SynchronizationContext rather than a control for cross-thread marshaling.

Исключение может быть вызвано, если поток, который должен обработать сообщение, больше не активен. An exception might be thrown if the thread that should process the message is no longer active.

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