C # The control created on one thread cannot be the parent of a control created on another thread

Source: Internet
Author: User

First, a new Class1 object is created in Form1 's form loading and a reference to itself is passed into its constructor, and a thread in the constructor of Class1. The method event that the thread is acting on is an Add method in this class. The content of the Add method is to put a textbox on the Form1.
However, there are several issues that you should be aware of in this process:
1. Which is the main thread? The so-called main thread is the first one that starts, starting with main. This form of Form1 is created by the main thread.
What is the thread of 2.Thread T? T is created by the main thread, and the action of T is to place a textbox on the form created by the main thread.
That is, the action of T is a form action that spans threads. Although the Checkforillegalcrossthreadcalls is set to False, there is also a control created on one thread that cannot be the parent of the control created on another thread.
Workaround:
1. Do not thread, operate only in one main thread. It is possible to add controls in the Class1, or write a method in the Form1 to add controls.
2. Through the agent to achieve. In the operation of the Form1 object
if (Form1. invokerequired)
{
Form1. Invoke (d);//d for proxy references created in the main thread
The method that the //d proxies should be to add the contents of the control
}
Else
{
Form1. Controls.Add (textBox1);//Direct Use
}
//Code
class Class1
{
Form1 F1;
TextBox TextBox1;
delegate void AddDelegate ();
adddelegate D;
Public Class1 (Form1 F1)
{
this.f1 = F1;
d=new adddelegate (F1.add ());//The add here is a method in Form1
thread t = new Thread (new ThreadStart (add));
T.start ();
}
Public Void Add ()
{
if (F1. invokerequired)
{
F1. Invoke (d); Using proxies
}
Else
{
F1. Controls.Add (New TextBox ());//... Call Directly
}
}
}

C # The control created on one thread cannot be the parent of a control created on another thread

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.