zoukankan      html  css  js  c++  java
  • .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显示结果

     

  • 相关阅读:
    树莓派常用Linux命令
    列出树莓派中系统中建立了哪些用户、哪些组?
    树莓派的用户管理
    树莓派变成一个Web服务器: nginx + php + sqlite
    树莓派做web服务器(nginx、Apache)
    树莓派修改更新源
    树莓派安装mysql
    树莓派2 购买心得
    python写的屏保程序
    win32下利用python操作printer
  • 原文地址:https://www.cnblogs.com/thomerson/p/12585199.html
Copyright © 2011-2022 走看看