C # WinForm Cross-thread access control

Source: Internet
Author: User
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:

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.