C# 跨线程访问控件
在做WinForm时,在UI线程之外调用控件会报异常:System.InvalidOperationException:“线程间操作无效: 从不是创建控件“label1”的线程访问它。”
我们只需在跨线程调用控件时增加如下代码:
if (this.InvokeRequired)
{
this.Invoke(new Action(() =>
{
lable1.Text = "Hello World!";
}));
}
如下是我的demo
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace test
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void ChangeControl()
{
if (this.InvokeRequired)
{
this.Invoke(new Action(() =>
{
lbl_msg.Text = "Hello Task!";
}));
}
}
private void btnTask_Click(object sender, EventArgs e)
{
Task.Run(()=> {
ChangeControl();
});
}
private void btnThread_Click(object sender, EventArgs e)
{
Thread thread = new Thread(()=>
{
if (this.InvokeRequired)
{
this.Invoke(new Action(() =>
{
lbl_msg.Text = "Hello Thread!";
}));
}
}
);
thread.IsBackground = true;
thread.Start();
}
}
}
程序运行结果