【C#】Winform程序Task跨线程访问控件
|
admin
2025年4月30日 12:35
本文热度 1436
|
方法1-控件对象.Invoke(Action<>,参数),同步执行卡UIInvoke 是同步的,它会阻塞调用线程,直到目标线程(创建控件的线程)完成所请求的操作。这意味着调用 Invoke 后,当前线程会等待,直到 UI 线程执行完指定的方法。
方法2-控件对象.BeginInvoke(Action<>,参数),异步执行不卡UI
BeginInvoke 是异步的,它会将操作放入 UI 线程的消息队列中,然后立即返回,不会阻塞调用线程。这使得调用线程可以继续执行其他操作,而无需等待 UI 更新完成。
方法3-Invoke((MethodInvoker)delegate
MethodInvoker 是一个无参数、无返回值的委托类型,用于表示可以被调用的方法在多线程编程中,特别是在 Windows 窗体应用程序中,MethodInvoker 常用于安全地更新 UI 控件,它可以被用作给 Invoke 和 BeginInvoke 方法传递的委托。
namespace _018_跨线程访问控件方法
{
public partial class 跨线程访问控件方法 : Form
{
public 跨线程访问控件方法()
{
InitializeComponent();
}
private void bt1_Click(object sender, EventArgs e)
{
Task t1 = Task.Run(() =>
{
for (int i = 1; i < 100; i++)
{
Thread.Sleep(500);
if (this.txtBox1.InvokeRequired)
{
this.txtBox1.Invoke(new Action<string>((st) =>
{
this.txtBox1.Text = st;
}), i.ToString());
}
}
});
}
private void bt2_Click(object sender, EventArgs e)
{
Task.Run(() =>
{
for(int i = 1;i < 100; i++)
{
Thread.Sleep(1000);
if (this.txtBox2.InvokeRequired)
{
this.txtBox2.BeginInvoke(new Action<string>((st) =>
{
this.txtBox2.Text += st+"、";
}),i.ToString());
}
}
});
}
private void bt3_Click(object sender, EventArgs e)
{
Task.Run(() =>
{
for (int i = 0; i < 100; i++)
{
Thread.Sleep(1000);
if (this.txtBox3.InvokeRequired|| this.txtBox3.InvokeRequired)
{
Invoke((MethodInvoker)delegate
{
this.txtBox3.Text = i.ToString();
this.txtBox4.Text = i.ToString();
});
}
}
});
}
}
}
该文章在 2025/4/30 14:56:47 编辑过