.Net 【Winform】 Invoke and BeginInvoke

1.为什么需要Invoke和BeginInvoke

  很多开发知道在一些耗时的操作用异步线程去实现,但往往会一些问题,例如程序卡死,这是由于多个线程共同操作UI导致的。

  Winform提供了Control的Invoke和BeginInvoke在非主线程上操作主线程UI。

2.如何使用Invoke和BeginInvoke

  不要在主线程使用Invoke和BeginInvoke

  在支线程中使用Invoke和BeginInvoke操作UI

3.Invoke和BeginInvoke的区别

  Invoke会阻塞当前支线程

  BeginInvoke不会阻塞当前支线程

4.代码示例

using System;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Thomerson.Winform
{
    public partial class Main : Form
    {
        public Main()
        {
            InitializeComponent();

            var content = @"Init
";
            WriteTxt(content);
            this.txt_content.AppendText(content);


            Task.Factory.StartNew(() =>
            {
                Thread.Sleep(3000);
                //this.Invoke(new Action(() =>
                this.BeginInvoke(new Action(() =>
                {
                Thread.Sleep(3000);
                    content = @"A*******
";
                    WriteTxt(content);
                    this.txt_content.AppendText(content);
                }));

                content = @"B*******
";
                WriteTxt(content);
                
                //this.Invoke(new Action(() =>
                this.BeginInvoke(new Action(() =>
                {
                    WriteTxt(content);
                    this.txt_content.AppendText(content);
                }));
                content = @"C*******
";
                WriteTxt(content);
            });

            content = @"End
";
            WriteTxt(content);
            this.txt_content.AppendText(content);
        }


        //Invoke
        //Init

        //End

        //A*******

        //B*******

        //B*******

        //C*******


        //BeginInvoke
        //Init

        //End

        //B*******

        //C*******

        //A*******

        //A*******



        private void WriteTxt(string content)
        {
            using (System.IO.StreamWriter file = new System.IO.StreamWriter($@"{Environment.CurrentDirectory}\log.txt", true))
            {
                file.WriteLine(content);
            }
        }
    }
}

Invoke显示结果

 

BeginInvoke显示结果

 

猜你喜欢

转载自www.cnblogs.com/thomerson/p/12585199.html