代码改变世界

C# 通过线程更新UI

2014-02-20 22:23  每天努力一点点  阅读(231)  评论(0编辑  收藏  举报

摘自: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;
			}
		}