zoukankan      html  css  js  c++  java
  • Control的Invoke和BeginInvoke

    1.Control.Invoke

    Invoke 会导致线程的阻塞,但是是顺序执行的,

    private void Form1_Load(object sender, EventArgs e)
    {
        listBox1.Items.Add("begin");
        listBox1.Invoke(new Action(() => { listBox1.Items.Add("invoke"); }));
        listBox1.Items.Add("after");
    }

    2.Control.BeginInvoke

    BeginInvoke 同样会导致线程的阻塞,在执行完主线程(UI线程)后才会执行,

    private void Form1_Load(object sender, EventArgs e)
    {
        listBox1.Items.Add("begin");
        listBox1.BeginInvoke(new Action(() => { listBox1.Items.Add("begininvoke"); }));
        listBox1.Items.Add("after");
    }

    若想要在线程执行结束之前执行 BeginInvoke,可以使用 EndInvoke,

    private void Form1_Load(object sender, EventArgs e)
    {
        listBox1.Items.Add("begin");
        var i = listBox1.BeginInvoke(new Action(() => { listBox1.Items.Add("begininvoke"); }));
        listBox1.EndInvoke(i);
        listBox1.Items.Add("after");
    }

    或者 BeginInvoke 会在一个 Invoke 调用前执行,

    private void Form1_Load(object sender, EventArgs e)
    {
        listBox1.Items.Add("begin");
        listBox1.BeginInvoke(new Action(() => { listBox1.Items.Add("begininvoke"); }));
        listBox1.Invoke(new Action(() => { listBox1.Items.Add("invoke"); }));
        listBox1.Items.Add("after");
    }

    Tips:

    如果 Invoke 在支线程中定义调用,那么它同样会在主线程(UI线程)中执行,也会阻塞主线程和支线程;

    如果 BeginInvoke 在支线程中定义调用,那么它也会在主线程(UI线程)中执行,也会阻塞主线程,但相对于支线程是异步的。

    Invoke 和 BeginInvoke 的主要作用是在支线程中访问 UI 线程

    private System.Timers.Timer myTimer;
    
    private void Form1_Load(object sender, EventArgs e)
    {
        //窗体打开时创建定时器,并设置执行频率时间,会创建新线程
        this.myTimer = new System.Timers.Timer(1000);
        //设置任务
        this.myTimer.Elapsed += new System.Timers.ElapsedEventHandler(myTimer_Elapsed);
        this.myTimer.AutoReset = true;
        this.myTimer.Enabled = true;
        this.myTimer.Start();
    }
    
    private void myTimer_Elapsed(object sender, ElapsedEventArgs e)
    {
        count++;
        label1.Invoke(new Action(() => { label1.Text = count.ToString() + "s"; }));
    }

    What's up with BeginInvoke?

  • 相关阅读:
    解决“ 故障模块名称: clr.dll ”
    关于阿里云专有网络搭建FTP服务器的深坑
    电脑异常断电,IDEA崩溃
    Winform 出现“Win已停止工作”解决方法
    C# WinForm控件、自定义控件整理(大全)
    cmd获取管理员权限等
    检测笔记本电池状态
    单片机
    常用工具、焊接技术
    元器件
  • 原文地址:https://www.cnblogs.com/jizhiqiliao/p/9963565.html
Copyright © 2011-2022 走看看