c#Thread多线程之跨线程-3
using System;
using System.Threading;
using System.Windows.Forms;
namespace CrossThreadDemo
{
public partial class Form1 : Form
{
// 执行顺序1:窗体加载
public Form1()
{
InitializeComponent();
}
// 执行顺序2:点击按钮
private void button1_Click(object sender, EventArgs e)
{
// 创建子线程
Thread thread = new Thread(UpdateText);
// 执行顺序3:启动子线程
thread.Start();
}
// 子线程方法
private void UpdateText()
{
// 执行顺序4:子线程运行
// ---------------- 错误写法(直接修改 → 报错!)----------------
// textBox1.Text = "子线程修改";
// ---------------- 正确写法(跨线程 Invoke)----------------
// 让主线程执行修改界面操作
textBox1.Invoke(new Action(() =>
{
// 执行顺序5:主线程安全修改控件
textBox1.Text = "跨线程修改成功!";
}));
}
}
}
Invoke:插队,让主线程执行代码
new Action(() => {}):要交给主线程做的任务
大括号内的代码:由主线程执行,100% 安全
————————————————————————————————————————————————————————————————————————

浙公网安备 33010602011771号