1.概要
其他线程需要改变ui的属性。但是其他线程是不能操作ui的属性的。使用Invoke解决
Invoke的注释
//
// 摘要:
// 在拥有此控件的基础窗口句柄的线程上执行指定的委托。
//
// 参数:
// method:
// 包含要在控件的线程上下文中调用的方法的委托。
//
// 返回结果:
// 正在被调用的委托的返回值,或者如果委托没有返回值,则为 null。
public object Invoke(Delegate method);
2.代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Invoke实验
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Task task = new Task(() =>
{
button1.Text = "关闭";
});
task.Start();
}
private void button2_Click(object sender, EventArgs e)
{
Task task = new Task(() =>
{
button1.Invoke(new EventHandler(delegate
{
button1.Text = "关闭";
}));
});
task.Start();
}
}
}
3.运行
4.补记(问题发生)
System.InvalidOperationException:“线程间操作无效: 从不是创建控件“button1”的线程访问它。”