This.invoke和this.begininvoke的区别?

应用场景

在多线程编程中,我们经常要在工作线程中去更新界面显示,而在多线程中直接调用界面控件的方法是错误的做法,Invoke和BeginInvoke就是为了解决这个问题。

个人总结

①This.begininvoke和this.invoke注册委托调用的方法都是等UI主线程执行到“windows消息泵”的时候才被调用,不是立即执行委托的,都是在UI线程中执行

②通常可以把耗时的操作放到子线程里执行,然后再调用BeginInvoke/Invoke方法

③Control的BeginInvoke是相对于工作线程(工作线程是调用BeginInvoke方法的线程)是异步的。
工作线程不管是UI线程还是子线程,Invoke需要阻塞工作线程执行,而BeginInvoke不需要阻塞工作线程执行。

测试

UI线程:

    private void button76_Click(object sender, EventArgs e)
    {
        Console.WriteLine("1");
        this.Invoke(new Action(() =>
        {
            Thread.Sleep(1000);
            Console.WriteLine("2");
        }));

        Console.WriteLine("3");
    }

    private void button85_Click(object sender, EventArgs e)
    {
        Console.WriteLine("4");
        this.BeginInvoke(new Action(() =>
        {
            Thread.Sleep(1000);
            Console.WriteLine("5");
        }));

        Console.WriteLine("6");
    }
}

输出结果如下:
在这里插入图片描述

子线程:


    private void button76_Click(object sender, EventArgs e)
    {
       Thread t  = new Thread(()=>
        {
            Console.WriteLine("1");
            this.Invoke(new Action(() =>
            {
                Thread.Sleep(10000);
                Console.WriteLine("2");
            }));

            Console.WriteLine("3");
        });
        t.Start();
    }

    private void button85_Click(object sender, EventArgs e)
    {
        Thread t = new Thread(() =>
        {
            Console.WriteLine("4");
            this.BeginInvoke(new Action(() =>
            {
                Thread.Sleep(10000);
                Console.WriteLine("5");
            }));

            Console.WriteLine("6");
        });
        t.Start();
    }
}

在这里插入图片描述

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值