WinForm解决UI假死

运行WinForm程序时,如果后台执行比较费时的操作,前天UI就会假死卡住,很影响使用感受,这里我们简单的解决一下这个问题

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WinForm
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 后台要执行的操作
        /// </summary>
        private void AAA()
        {
            for (int i = 0; i < 999999999; i++) //模拟耗时的操作
            {
                if (i % 9999999 == 0) //每隔9999999次循环ui更新下百分比 
                {
                    this.label1.Invoke((Action<int>)delegate(int a) //在控件对象所在的线程上执行委托
                    {
                        this.label1.Text = a.ToString() + "%";
                    }, i / 9999999);
                }
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            ((Action)AAA).BeginInvoke(null, null); //调用委托的异步执行方法,回调函数为空 
        }
    }
}
原文地址:https://www.cnblogs.com/luludongxu/p/6065987.html