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); //調用委托的異步執行方法,回調函數為空 
        }
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM