private void button2_Click(object sender, EventArgs e)
{// 启动线程
d = 0;
Thread showThread = new Thread(new ThreadStart(CallControl));
showThread.Start();
}
int d;// 定义变量
protected delegate void UpdateFormControlText(string str);//定义一个委托
protected void updateFormControlText(string str)
{//定义更新控件的方法
textBox1.Text = str;
return;
}
//线程中安全访问窗体控件
private void CallControl()
{
if (this.InvokeRequired)
{
//用更新控件的方法updateControlText实例化一个委托update
UpdateFormControlText update = new UpdateFormControlText(updateFormControlText);
//调用窗体Invoke方法
this.Invoke(update, Convert.ToString(++d));
}
else
{
textBox1.Text = (++d).ToString();
}
}【多线程】线程访问另一线程中窗体的控件
最新推荐文章于 2023-05-28 14:56:01 发布
本文介绍了一个使用C#实现线程安全更新UI的方法。通过定义委托并使用Invoke方法来确保在非UI线程中可以安全地更新textBox控件的内容。此方法适用于需要在后台线程中更新界面的应用场景。
225

被折叠的 条评论
为什么被折叠?



