C # use a thread to change the properties of the Form Control in winform

Source: Internet
Author: User

Windows Forms controls are generally not thread-safe, so. NET framework to prevent the control from being accessed by multiple threads, which may lead to inconsistent control states, during debugging, CLR-debugger will throw an invalidoperationexception to be "recommended"ProgramPossible risks of member programs. Of course, you can also ignore the invalidoperationexception. In non-Debug status, this exception will not be thrown. CLR-debugger monitors possible inconsistent access to handle, and expected to achieve a more stableCode. There are two ways to solve this problem: first, in some cases, we do not need this "suggestion", which will cause unnecessary trouble during debugging; second, adapt to the "suggestion" and adjust the programming model.

Solution:

1. Add in the form constructor or in the main of the application

Control. checkforillegalcrossthreadcils = False ;

Ignore cross-thread invalidoperationexception.

2. Accept the good faith suggestion of cross-thread invalidoperationexception, and use system. componentmodel. isynchronizeinvoke's invokerequired and invoke methods. This code is valid for most Windows controls. The purpose of this Code is to ensure that the main thread of the control is uniquely called get_handle.

Private   Void Safesettext ( String Text)
{
If ( This . Invokerequired)
{
_ Safesettextcall call = Delegate ( String S)
{
This . Textbox1.text = s;
};

This . invoke (call, text);
}
else
This . textbox1.text = text;
}

private DeleGate void _ safesettextcall ( string text );

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.