跨线程的访问控件是需要用delegate的,给你个msdn上的例子参考一下:
不好意思,今天上微软的网站很慢,给不出地址,文章的题目是
Make Thread-Safe Calls to Windows Forms Controls,大概得代码是这样的。
//定义一个访问控件使用的委托
delegate void SetTextCallback(string text); //启动线程的,不解释了。
private void setTextSafeBtn_Click(
object sender,
EventArgs e)
{
this.demoThread =
new Thread(new ThreadStart(this.ThreadProcSafe)); this.demoThread.Start();
} // This method is executed on the worker thread and makes
// a thread-safe call on the TextBox control.
private void ThreadProcSafe()
{
this.SetText("This text was set safely.");
} // This method demonstrates a pattern for making thread-safe
// calls on a Windows Forms control.
//
// If the calling thread is different from the thread that
// created the TextBox control, this method creates a
// SetTextCallback and calls itself asynchronously using the
// Invoke method.
//
// If the calling thread is the same as the thread that created
// the TextBox control, the Text property is set directly. private void SetText(string text)
{
//这里判断访问控件的线程是否是创建该控件的线程,如果不是则调用委托,
//委托同样是调用这个函数,区别是委托是从创建该控件的线程来的。
if (this.textBox1.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
this.Invoke(d, new object[] { text });
}
else //如果是则直接访问控件属性。
{
this.textBox1.Text = text;
}
}
不好意思,今天上微软的网站很慢,给不出地址,文章的题目是
Make Thread-Safe Calls to Windows Forms Controls,大概得代码是这样的。
//定义一个访问控件使用的委托
delegate void SetTextCallback(string text); //启动线程的,不解释了。
private void setTextSafeBtn_Click(
object sender,
EventArgs e)
{
this.demoThread =
new Thread(new ThreadStart(this.ThreadProcSafe)); this.demoThread.Start();
} // This method is executed on the worker thread and makes
// a thread-safe call on the TextBox control.
private void ThreadProcSafe()
{
this.SetText("This text was set safely.");
} // This method demonstrates a pattern for making thread-safe
// calls on a Windows Forms control.
//
// If the calling thread is different from the thread that
// created the TextBox control, this method creates a
// SetTextCallback and calls itself asynchronously using the
// Invoke method.
//
// If the calling thread is the same as the thread that created
// the TextBox control, the Text property is set directly. private void SetText(string text)
{
//这里判断访问控件的线程是否是创建该控件的线程,如果不是则调用委托,
//委托同样是调用这个函数,区别是委托是从创建该控件的线程来的。
if (this.textBox1.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
this.Invoke(d, new object[] { text });
}
else //如果是则直接访问控件属性。
{
this.textBox1.Text = text;
}
}
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货