在我的应用程序中,我需要执行一系列初始化步骤,这些步骤需要7-8秒才能完成,在此期间,我的UI变得没有响应。为了解决这个问题,我在一个单独的线程中执行初始化:
public void Initialization()
{
Thread initThread = new Thread(new ThreadStart(InitializationThread));
initThread.Start();
}
public void InitializationThread()
{
outputMessage("Initializing...");
//DO INITIALIZATION
outputMessage("Initialization Complete");
}我读过一些关于BackgroundWorker的文章,关于它应该如何让我的应用程序保持响应,而不需要编写线程来执行冗长的任务,但是我还没有成功地尝试实现它,有人能告诉我如何使用BackgroundWorker做到这一点吗
发布于 2014-06-03 02:06:12
您可能还想研究一下使用Task而不是后台工作者。
最简单的方法是在您的示例中使用Task.Run(InitializationThread);。
使用任务而不是后台工作者有几个好处。例如,.net 4.5中的新异步/等待功能使用Task进行线程处理。以下是有关Task https://docs.microsoft.com/en-us/dotnet/api/system.threading.tasks.task的一些文档
发布于 2015-05-31 13:21:05
using System;
using System.ComponentModel;
using System.Threading;
namespace BackGroundWorkerExample
{
class Program
{
private static BackgroundWorker backgroundWorker;
static void Main(string[] args)
{
backgroundWorker = new BackgroundWorker
{
WorkerReportsProgress = true,
WorkerSupportsCancellation = true
};
backgroundWorker.DoWork += backgroundWorker_DoWork;
//For the display of operation progress to UI.
backgroundWorker.ProgressChanged += backgroundWorker_ProgressChanged;
//After the completation of operation.
backgroundWorker.RunWorkerCompleted += backgroundWorker_RunWorkerCompleted;
backgroundWorker.RunWorkerAsync("Press Enter in the next 5 seconds to Cancel operation:");
Console.ReadLine();
if (backgroundWorker.IsBusy)
{
backgroundWorker.CancelAsync();
Console.ReadLine();
}
}
static void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 0; i < 200; i++)
{
if (backgroundWorker.CancellationPending)
{
e.Cancel = true;
return;
}
backgroundWorker.ReportProgress(i);
Thread.Sleep(1000);
e.Result = 1000;
}
}
static void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
Console.WriteLine("Completed" + e.ProgressPercentage + "%");
}
static void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled)
{
Console.WriteLine("Operation Cancelled");
}
else if (e.Error != null)
{
Console.WriteLine("Error in Process :" + e.Error);
}
else
{
Console.WriteLine("Operation Completed :" + e.Result);
}
}
}
} 此外,请参考以下链接,您将了解Background的概念
http://www.c-sharpcorner.com/UploadFile/1c8574/threads-in-wpf/
发布于 2013-09-24 04:39:28
我发现这个(WPF Multithreading: Using the BackgroundWorker and Reporting the Progress to the UI. link)包含了@Andrew答案中缺失的其余细节。
我发现有一件事非常有用,那就是工作线程不能访问MainWindow的控件(在它自己的方法中),但是当在主窗口事件处理程序中使用委托时,这是可能的。
worker.RunWorkerCompleted += delegate(object s, RunWorkerCompletedEventArgs args)
{
pd.Close();
// Get a result from the asynchronous worker
T t = (t)args.Result
this.ExampleControl.Text = t.BlaBla;
};https://stackoverflow.com/questions/5483565
复制相似问题