后台工作者在WPF中无法正常工作 [英] Background worker does not work properly in WPF
本文介绍了后台工作者在WPF中无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
大家好...
我想在datagrid中显示临时文件,因此这是一个长期的过程,我在C#.net WPF应用程序中使用后台工作程序.
我的代码是
Hi Everyone...
i want to show Temporary files in a datagrid , hence it is a long term process i use background worker in my C# .net WPF application .
my Code is
private System.ComponentModel.BackgroundWorker _background = new System.ComponentModel.BackgroundWorker();
private void button1_Click(object sender, RoutedEventArgs e)
{
_background.RunWorkerAsync();
}
public MainWindow()
{
InitializeComponent();
this._background.DoWork += new DoWorkEventHandler(_background_DoWork);
this._background.RunWorkerCompleted += new
RunWorkerCompletedEventHandler(_background_RunWorkerCompleted);
this._background.WorkerReportsProgress = true;
_background.WorkerSupportsCancellation = true;
}
void _background_DoWork(object sender, DoWorkEventArgs e)
{
this.Dispatcher.Invoke((Action)(() =>
{
try
{
FileInfo[] files = new
DirectoryInfo(System.IO.Path.GetTempPath()).GetFiles();
foreach (FileInfo fi in files)
{
if (fi != null)
{
dataGrid1.Items.Add(fi);
}
}
}
catch { }
}));
}
void _background_RunWorkerCompleted(object sen, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled)
{
MessageBox.Show("Cancelled");
}
else if (e.Error != null)
{
MessageBox.Show("Exception Thrown");
}
}
所有代码都在运行,但是在加载datagrid时挂起,这意味着程序运行时我的UI没有响应.
要在上述条件下平稳地运行后台工作者,需要进行哪些修改?
谢谢
All the code is running but it hangs when datagrid is loading means my UI does not response when program is running .
What modification is needed to run background worker smoothly in the above condition ?
Thank You
推荐答案
跟随代码,您完全破坏了在后台线程上进行工作的目的.
在后台线程的DoWork方法中,您告诉UI线程(this.Dispatcher.Invoke)执行长时间运行的代码,完全删除了后台线程的要点.
后台线程应该是调用将文件添加到datagrid的方法.
我相信您正在寻找这样的东西:
Following your code, you completely wrecked the purpose of doing work on a background thread.
In the DoWork method, on a background thread, you told the UI thread (this.Dispatcher.Invoke) to execute the long running code, completely removing the point of the background thread.
The background thread should be Invoking a method to add the file to the datagrid.
I believe you''re looking for something like this:
void _background_DoWork(object sender, DoWorkEventArgs e)
{
FileInfo[] files = new
DirectoryInfo(System.IO.Path.GetTempPath()).GetFiles();
foreach (FileInfo fi in files)
{
if (fi != null)
{
this.Dispatcher.BeginInvoke((Action)(() => dataGrid1.Items.Add(fi)));
}
}
}
}
您好,
您应该在后台工作器的主循环中添加一小段睡眠,以允许UI线程刷新显示.
尝试在您的foreach循环中添加类似的内容
Hello,
You should add to the background worker a short sleep in its main loop to allow the UI thread to refresh the display.
Try adding something like this to your foreach loop
// This sleep will allow the UI thread to refresh the display.
totalCounter++;
if (totalCounter % 100 == 0)
System.Threading.Thread.Sleep(80);
这篇关于后台工作者在WPF中无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文