The control in the main thread is manipulated through a child thread, but there is a problem (1) that the TextBox control is created in the main thread and is not created in the child thread, that is, it is accessed from a thread that is not creating the control. So how do you solve cross-threading calls to Windows Forms controls? You can invoke a Windows Forms control across threads by using thread delegation . Here is an example of the previous change. The code is as follows:
usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel;usingSystem.Data;usingSystem.Drawing;usingSystem.Linq;usingSystem.Text;usingSystem.Windows.Forms;usingSystem.Threading;//add a thread's namespace namespaceppp{ Public Partial classForm1:form { PublicForm1 () {InitializeComponent (); } Thread t; //Defining thread Variables Private voidButton1_Click (Objectsender, EventArgs e) {T=NewThread (NewThreadStart (THREADP));//Instantiating ThreadsT.start ();//Start Thread } Private Delegate voidSetText ();//defines a thread delegatecustom Method Threadp, which is used primarily for thread invocation. The code is as follows: Public voidthreadp () {SetText D=NewSetText (threading);//instantiate a delegate This. Invoke (d);//executes the specified delegate on the thread that owns the underlying form handle of this controlThe custom method threading, primarily for delegate invocation. The code is as follows: Public voidThreading () {TextBox1.Text="implementing controls in the main thread of the child threads"; T.abort ();//Close Thread } }}
How to call Windows Forms controls across threads