前言
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<string> GetMessage()
{
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沒有處于假死狀態,窗體可以隨意拖動。首先需要明確一點: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 編輯過