多线程执行顺序invoke、Task
代码
public partial class Form1 : Form
{
AutoResetEvent a = new AutoResetEvent(false);//自动复位
AutoResetEvent b = new AutoResetEvent(false);
AutoResetEvent c = new AutoResetEvent(false);
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
a.Set();
Task.Run(() => A());//开始进程
Task.Run(() => B());
Task.Run(() => C());
}
private void A()
{
while (true)
{
a.WaitOne();
this.Invoke(new Action(() => { this.richTextBox1.Text += "开始-读取PLC\r\n"; }));
Thread.Sleep(1000);
this.Invoke(new Action(() => { this.richTextBox1.Text += "完成-读取PLC\r\n"; }));
Thread.Sleep(1000);
b.Set();
}
}
private void B()
{
while (true)
{
b.WaitOne();
this.Invoke(new Action(() => { this.richTextBox2.Text += "开始-绘制曲线\r\n"; }));
Thread.Sleep(1000);
this.Invoke(new Action(() => { this.richTextBox2.Text += "开始-绘制曲线\r\n"; }));
Thread.Sleep(1000);
c.Set();
}
}
private void C()
{
while (true)
{
c.WaitOne();
this.Invoke(new Action(() => { this.richTextBox3.Text += "开始-保存数据库\r\n"; }));
Thread.Sleep(1000);
this.Invoke(new Action(() => { this.richTextBox3.Text += "开始-保存数据库\r\n"; }));
Thread.Sleep(1000);
a.Set();
}
}
}
执行效果

Invoke等效分解
Invoke主要用于子线程中对UI页面更新数据
完整Invoke

匿名Invoke



浙公网安备 33010602011771号