TextBox和Thread

lol*_*ola 3 c# textbox

为什么这不起作用?

该计划停止: 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)";           
     }
 }
Run Code Online (Sandbox Code Playgroud)

Jus*_*ier 5

在Windows中,控件只能由创建它的线程更新.您需要使用Control.Invoke对UI线程的方法调用来更新文本.

在MSDN Control.Invoke页面上有一个这样的例子 .


Aar*_*ght 5

Control.Invoke从后台线程执行这些操作时需要使用:

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

如果您正在编写可以从后台线程运行的通用代码,您还可以检查Control.InvokeRequired属性,如:

if (textBox1.InvokeRequired)
{
    textBox1.Invoke(...);
}
else
{
    // Original code here
}
Run Code Online (Sandbox Code Playgroud)