如何使用 WPF 后台工作者 [英] How to use WPF Background Worker
问题描述
在我的应用程序中,我需要执行一系列初始化步骤,这些步骤需要 7-8 秒才能完成,在此期间我的 UI 变得无响应.为了解决这个问题,我在一个单独的线程中执行初始化:
In my application I need to perform a series of initialization steps, these take 7-8 seconds to complete during which my UI becomes unresponsive. To resolve this I perform the initialization in a separate thread:
public void Initialization()
{
Thread initThread = new Thread(new ThreadStart(InitializationThread));
initThread.Start();
}
public void InitializationThread()
{
outputMessage("Initializing...");
//DO INITIALIZATION
outputMessage("Initialization Complete");
}
我已经阅读了几篇关于 BackgroundWorker
的文章,以及它应该如何让我的应用程序保持响应,而不必编写线程来执行冗长的任务,但我没有成功尝试要实现它,谁能告诉我如何使用 BackgroundWorker
来做到这一点?
I have read a few articles about the BackgroundWorker
and how it should allow me to keep my application responsive without ever having to write a thread to perform lengthy tasks but I haven't had any success trying to implement it, could anyone tell how I would do this using the BackgroundWorker
?
推荐答案
- 添加使用
using System.ComponentModel;
- 声明后台工作人员:
private readonly BackgroundWorker worker = new BackgroundWorker();
- 订阅事件:
worker.DoWork += worker_DoWork;
worker.RunWorkerCompleted += worker_RunWorkerCompleted;
- 实现两种方法:
private void worker_DoWork(object sender, DoWorkEventArgs e)
{
// run all background tasks here
}
private void worker_RunWorkerCompleted(object sender,
RunWorkerCompletedEventArgs e)
{
//update ui once worker complete his work
}
- 在需要时运行异步工作线程.
worker.RunWorkerAsync();
跟踪进度(可选,但通常很有用)
Track progress (optional, but often useful)
a) 订阅 ProgressChanged
事件并在 DoWork
a) subscribe to ProgressChanged
event and use ReportProgress(Int32)
in DoWork
b) 设置 worker.WorkerReportsProgress = true;
(归功于@zagy)
b) set worker.WorkerReportsProgress = true;
(credits to @zagy)
这篇关于如何使用 WPF 后台工作者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!