C # WinForm cross-thread access control,

Source: Internet
Author: User

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:

 

 







 

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.