LOGO OA教程 ERP教程 模切知識交流 PMS教程 CRM教程 開發文檔 其他文檔  
 
網站管理員

WinForm 中解決 UI 假死問題的方法

admin
2024年12月27日 22:53 本文熱度 512

前言

WinForm中的UI假死其實是個老生常談的問題了,但最近還是很多人問我該如何解決,所以今天就來說明一下如何解決UI假死的問題。

實驗程序界面如下圖所示:

正文

方法一 async + await + Task

首先看下面一段代碼:

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

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        // 開始
        private void btnStart_Click(object sender, EventArgs e)
        {
            string message = GetMessage();
            MessageBox.Show(message);
        }

        // 一個耗時任務
        private string GetMessage()
        {
            Thread.Sleep(10000);
            return "Hello World";
        }
    }
}

在上面的代碼中,GetMessage()方法耗時10秒鐘,如果你點擊按鈕,那么在10秒鐘內窗體將處于假死狀態。

這種情況很常見,之所以會造成UI假死的原因也很簡單:某個函數耗時太久。

在遇見這種情況的時候,我們就可以考慮使用async + await + Task來解決,代碼如下:

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

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        // 開始
        private async void btnStart_Click(object sender, EventArgs e)
        {
            string message = await GetMessage();
            MessageBox.Show(message);
        }

        // 一個耗時任務
        private async Task<stringGetMessage()
        {
            return await Task<string>.Run(() =>
            {
                Thread.Sleep(10000);
                return "Hello World";
            });
        }
    }
}

運行之后點擊按鈕,你會發現UI沒有假死,窗體可以隨意拖動了。

方法二:使用BackgroundWorker組件

在很多時候,我們需要動態顯示當前的程序執行進度,以便讓用戶了解程序已經執行到哪一步了。

很多同志都會這么寫:

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

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        // 開始
        private void btnStart_Click(object sender, EventArgs e)
        {
            int max = pgbStatus.Maximum;
            for (int i = 1; i <= max; i++)
            {
                pgbStatus.Value++;
                Thread.Sleep(1000);
            }
        }
    }
}

功能確實是實現了,進度條能夠顯示當前執行的進度,可惜UI還是處于假死狀態,所以用戶體驗還是不好。

其實WinForm已經給我們提供了一個處理多線程任務的組件BackgroundWorker,使用它可以輕松讓你的程序告別UI假死,如下圖所示:

代碼如下:

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

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            this.bgw.WorkerReportsProgress = true;
            this.bgw.WorkerSupportsCancellation = true;
            this.bgw.DoWork += DoWork;
            this.bgw.ProgressChanged += ProgressChanged;
            this.bgw.RunWorkerCompleted += RunWorkerCompleted;
        }

        // 開始
        private void btnStart_Click(object sender, EventArgs e)
        {
            if (bgw.IsBusy)
            {
                return;
            }
            bgw.RunWorkerAsync();
        }

        // DoWork
        private void DoWork(object sender, DoWorkEventArgs e)
        {
            int max = pgbStatus.Maximum;
            for (int i = 1; i <= max; i++)
            {
                bgw.ReportProgress(i);
                Thread.Sleep(1000);
            }
        }

        // ProgressChanged
        private void ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            pgbStatus.Value = e.ProgressPercentage;
        }

        // RunWorkerCompleted
        private void RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            MessageBox.Show("完成");
        }
    }
}

運行程序點擊按鈕,你會發現UI沒有處于假死狀態,窗體可以隨意拖動。
方法三:Task + 委托(回調函數)
首先需要明確一點:UI線程位于主線程,如果想要在子線程里更新UI狀態,必須要將其切換到主線程,最后進行更新操作。
UI控件一般會提供Invoke、InvokeRequired,其中InvokeRequired用于判斷是否有子線程在更新UI控件,如果有則返回true,Invoke用于將控制權切換到UI線程,代碼如下:

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

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        // 開始
        private void btnStart_Click(object sender, EventArgs e)
        {
            Task task = Task.Run(() =>
            {
                int max = pgbStatus.Maximum;
                for (int i = 1; i <= max; i++)
                {
                    UpdateValue(i);
                    Thread.Sleep(1000);
                }
            });
        }

        // 處理線程
        private void UpdateValue(int num)
        {
            if (pgbStatus.InvokeRequired)
            {
                pgbStatus.Invoke(new Action<int>(UpdateValue), new object[] { num });
            }
            else
            {
                pgbStatus.Value = num;
            }
        }
    }
}

方法三也可以解決UI的假死問題,當然也不一定要用Task,利用Thread也可以實現一樣的效果。
總結
通過上述方法,可以有效地解決 WinForms 應用程序中 UI 假死的問題。選擇哪種方法取決于具體的場景和需求。BackgroundWorker 和 Task+ async/await 是最常用和推薦的方法,因為它們簡單易用且功能強大。ThreadPool和手動創建線程則適用于需要更高靈活性的場景。
無論選擇哪種方法,都要注意在更新 UI 時使用 Invoke或 BeginInvoke,以確保線程安全。
最后
如果你覺得這篇文章對你有幫助,不妨點個贊支持一下!你的支持是我繼續分享知識的動力。如果有任何疑問或需要進一步的幫助,歡迎隨時留言。也可以加入微信公眾號[DotNet技術匠] 社區,與其他熱愛技術的同行一起交流心得,共同成長!

作者:碼農家園

出處:codenong.com/cs106719464/
聲明:網絡內容,僅供學習,尊重版權,侵權速刪,歉意致謝!


該文章在 2024/12/28 11:58:25 編輯過
關鍵字查詢
相關文章
正在查詢...
點晴ERP是一款針對中小制造業的專業生產管理軟件系統,系統成熟度和易用性得到了國內大量中小企業的青睞。
點晴PMS碼頭管理系統主要針對港口碼頭集裝箱與散貨日常運作、調度、堆場、車隊、財務費用、相關報表等業務管理,結合碼頭的業務特點,圍繞調度、堆場作業而開發的。集技術的先進性、管理的有效性于一體,是物流碼頭及其他港口類企業的高效ERP管理信息系統。
點晴WMS倉儲管理系統提供了貨物產品管理,銷售管理,采購管理,倉儲管理,倉庫管理,保質期管理,貨位管理,庫位管理,生產管理,WMS管理系統,標簽打印,條形碼,二維碼管理,批號管理軟件。
點晴免費OA是一款軟件和通用服務都免費,不限功能、不限時間、不限用戶的免費OA協同辦公管理系統。
Copyright 2010-2025 ClickSun All Rights Reserved

黄频国产免费高清视频,久久不卡精品中文字幕一区,激情五月天AV电影在线观看,欧美国产韩国日本一区二区
在线天天看片免费 | 色婷婷六月亚洲婷婷6月 | 亚洲码一区二区三区在线看 | 日本特黄特大视频 | 色婷婷在线播放看片 | 一日本道a高清免费播放 |