The problem arises:
The error dialog box appears when WinForm handles the control of multithreaded access to the main thread:
Solution:
Scenario One: Remove the security check for thread access to the main thread UI control, using:
Control.checkforillegalcrossthreadcalls = false;
Scenario Two: Using a delegate, the UI control action on the main thread pushes the thread's message queue, using the method: The Invoke method and the BeginInvoke method, the previous one is the synchronous method, the latter is the asynchronous method;
The program code that uses the synchronous invoke method is tested as follows:
Note: Using the asynchronous BeginInvoke method and the synchronous invoke method, the Invoke method can be replaced with the BeginInvoke method.
Scenario Three: Using the synchronization context: The SynchronizationContext method, which takes the contextual information of the main thread, and then pushes the Access UI control method to the message queue in the UI context, using post or send;
Scenario Four: In the namespace: There's a system.componentmodel. The BackgroundWorker class, which is executed in a separate thread, copies the official website description:
The code is as follows, tested by:
problem Extension:
Why add a TextBox control on WinForm, and then access the UI main thread control through another thread, without error, normal pass??? Please master enlighten!!!
The figure is as follows: