为什么这不起作用?
该计划停止: 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)
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)
归档时间: |
|
查看次数: |
2013 次 |
最近记录: |