【发布时间】:2014-03-05 17:35:33
【问题描述】:
我有以下代码, 正如您所看到的,后台工作人员搜索文件,并且在进行中更改的事件文件被添加到列表视图中,但是由于有很多文件被添加到列表视图中,UI 变得无响应,我可以在循环中休眠线程但是我认为这不是一个好习惯,防止 UI 冻结的最佳方法是什么?
更详细地说,listview 是表单上的表单控件。
void bg_DoWork(object sender, DoWorkEventArgs e)
{
Stack<string> dirs = new Stack<string>(20);
dirs.Push(e.Argument.ToString());
while (dirs.Count > 0)
{
string currentDir = dirs.Pop();
string[] subDirs;
try { subDirs = System.IO.Directory.GetDirectories(currentDir); }
catch (UnauthorizedAccessException) { continue; }
catch (System.IO.DirectoryNotFoundException) { continue; }
string[] files = null;
try { files = System.IO.Directory.GetFiles(currentDir); }
catch (UnauthorizedAccessException) { continue; }
catch (System.IO.DirectoryNotFoundException) { continue; }
foreach (var file in files) { bg.ReportProgress(0, file); }
foreach (string str in subDirs) { dirs.Push(str); }
}
}
void bg_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
listView1.Items.Add(e.UserState.ToString());
}
【问题讨论】:
-
你能多显示一点上下文吗?你怎么称呼后台工作人员?
listView1是 Windows 窗体控件吗? -
如果你建立一个完整的列表,然后在_WorkComplete 事件中将它添加到你的listView 中,它是如何执行的?还是操作太慢而不合适?
-
@IainBallard 是的 listview 是一个控件。
-
@patchandthat 我可能会这样做,还没有尝试过,但是在列表视图中添加一个巨大的列表有什么区别?我的意思是,这可能仍然占用 UI。
-
如果目录中有很多文件,使用进度(0,文件)更新 UI 会使 UI 不得不做大量工作......
标签: c# user-interface backgroundworker