Detailed graphic and text explanation of C# WinForm cross-thread access control

黄舟
Release: 2017-09-16 11:09:53
Original
3903 people have browsed it

The problem occurs:

# When WinForm handles multi-threaded access to the main thread's controls, the following figure will appear: Error dialog shown:

Solution:

Solution 1: Remove the security check for thread access to main thread UI controls, use :

 Control.CheckForIllegalCrossThreadCalls = false;
Copy after login

Solution 2: Use delegation to push the UI control operation of the main thread to the message queue of the thread. The method used is : Invoke method and BeginInvoke method, the former is a synchronous method and the latter is an asynchronous method;

The program code for using the synchronous invoke method is as follows, which has passed the test:

Note: The process of using the asynchronous BeginInvoke method is the same as the synchronous invoke method. Just replace the invoke method with the BeginInvoke method;

Option 3: Use the synchronization context: SynchronizationContext method, the The method is to obtain the context information of the main thread, and then push the access UI control method to the message queue of the UI context in the child thread, using POST or Send;

Option 4: There is a BackgroundWorker class in the namespace: System.ComponentModel. It is executed in a separate thread. The following figure is copied from the official website description:

The code is as follows, the test passed:

Question expansion:

Why add the Textbox control to Winform, and then access the control of the UI main thread through another thread, do not report errors, pass normally? ? ? Please give me some advice from the experts! ! !

The picture is as follows:

The above is the detailed content of Detailed graphic and text explanation of C# WinForm cross-thread access control. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template