TextBox and Thread

Why is this not working?

The program stops: this.textBox1.Text = "(New text)";

 Thread demoThread;
 private void Form1_Load(object sender, EventArgs e)
 {
     this.demoThread = new Thread(new ThreadStart(this.ThreadProcUnsafe));
     this.demoThread.Start();

     textBox1.Text = "Written by the main thread.";
 }

 private void ThreadProcUnsafe()
 {
     while (true)
     {
         Thread.Sleep(2000);
         this.textBox1.Text = "(New text)";           
     }
 }
+3
source share
4 answers

You need to use Control.Invokewhen performing these operations from a background thread:

private void ThreadProcUnsafe()
{
    while (true)
    {
        Thread.Sleep(2000);
        textBox1.Invoke(new Action(() =>
        {
            textBox1.Text = "(New Text)";
        }));
    }
}

If you are writing generic code that can be run from a background thread, you can also check the property Control.InvokeRequired, as in:

if (textBox1.InvokeRequired)
{
    textBox1.Invoke(...);
}
else
{
    // Original code here
}
+5
source

In windows, a control can only be updated by the thread that created it. You must use Control.Invoketo route the method call to the user interface thread to update the text.

Here is an example of this on the MSDN Control.Invoke page .

+5
source

Windows . , , .

Control.Invoke BeginInvoke - - .

+2
source

Although I recommend using Invokeor BeginInvoke(after the call InvokeRequired, of course), you can prevent cross-thread exceptions altogether by calling this from your form or UserControl:

CheckForIllegalCrossThreadCalls = false;

( CheckForIllegalCrossThreadCallsis a static property Control)

If you decide to do this, you may get some strange results in the user interface.

+2
source

Source: https://habr.com/ru/post/1739039/


All Articles