C#中默认不允许在非UI线程中对UI控件进行操作
但如果我们想在子线程中操作空间可以使用通过控件的.Invoke方法
代码如下:
private void Chang()
{
//在线程中通过控件的.Invoke方法更新UI
while (true)
{
String str1 ="轻舟已过万重山";
this.SetText(str1);
}
}
private void SetText(String text)
{
if (this.label1.InvokeRequired)//此线程不为UI线程为true
{
while (!this.label1.IsHandleCreated)
{
//解决窗体关闭时出现“无法访问已释放的对象“的异常
if (this.label1.Disposing || this.label1.IsDisposed)
return;
}
SetTextCallback d = new SetTextCallback(SetText);
this.label1.Invoke(d, new object[] { text });
}
else
{
this.label1.Text = text;//没问题则改变label控件显示值(text)
}
}
private void FuiStart()
{
Thread FuiThread = new Thread(new ThreadStart(this.Chang));
FuiThread.IsBackground = true;
FuiThread.Start();//启动线程
}
运用此种方法可以在非UI线程中对UI控件进行一定的操作