winform程序backgroundworker或者异步中修改控件内容需要判断控件的InvokeRequired,然后使用委托执行更改控件内容的操作。
代码
using System; using System.Threading; using System.Windows.Forms; namespace WindowsFormsApp1 { public partial class Form2 : Form { public Form2() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { new Thread(Work).Start();//开启线程不卡死主线程 } private void Work() { Thread.Sleep(5000); string msg = "abcdefg"; UpdateMsg(msg); } private void UpdateMsg(string msg) { if (this.txtwords.InvokeRequired) { Action<string> action = UpdateMsg; this.Invoke(action, msg); return; } this.txtwords.Text = msg; } } }