C # WinForm cross-thread access control,
Problem:
When WinForm processes multi-threaded controls that access the main thread, an error dialog box is displayed:
Solution:
Solution 1: remove the security check for the main thread UI control accessed by the thread, and use:
Control.CheckForIllegalCrossThreadCalls = false;
Solution 2: Use delegation to push the UI control operations of the main thread to the Message Queue of the thread. The methods used are: Invoke method and BeginInvoke method. The first method is synchronous, the latter is an Asynchronous Method;
The program code using the synchronous invoke method is as follows and has passed the test:
Note: The asynchronous BeginInvoke method is the same as the synchronous invoke method. You can replace the invoke method with the BeginInvoke method;
Solution 3: Use the synchronous context: SynchronizationContext method 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 subthread, use POST or Send;
Solution 4:Namespace:There isThe BackgroundWorker class is executed in a separate thread. Copy the description on the official website:
The Code is as follows:
Problem extension:
Why does one add a TextBox Control on winform and access the control of the UI main thread through another thread? No error is reported and the control passes normally ??? Please enlighten me !!!
The figure is as follows: