C# 通过线程更新UI

时间:2024-09-17 10:36:44

摘自:http://msdn.microsoft.com/zh-cn/library/ms171728(en-us,VS.80).aspx

关键代码(form中增加):

delegate void SetTextCallback(string text);
private Thread demoThread = null;
private void setTextSafeBtn_Click(
object sender,
EventArgs e)
{
this.demoThread =
new Thread(new ThreadStart(this.ThreadProcSafe)); this.demoThread.Start();
}
private void ThreadProcSafe()
{
this.SetText("This text was set safely.");
}
private void SetText(string text)
{
// InvokeRequired required compares the thread ID of the
// calling thread to the thread ID of the creating thread.
// If these threads are different, it returns true.
if (this.textBox1.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
this.Invoke(d, new object[] { text });
}
else
{
this.textBox1.Text = text;
}
}