【发布时间】:2014-03-20 13:02:51
【问题描述】:
我想做并且一直致力于开发的是一个标准类,我可以使用它来检索所有子目录(及其子目录和文件等)和文件。
WalkthroughDir(Dir)
Files a
Folders b
WalkthroughDir(b[i])
简单的递归目录搜索。
以此为基础,我想将其扩展为在以下情况下触发事件:
- 找到一个文件;
- 找到一个目录;
-
搜索完成
private void GetDirectories(string path) { GetFiles(path); foreach (string dir in Directory.EnumerateDirectories(path)) { if (DirectoryFound != null) { IOEventArgs<DirectoryInfo> args = new IOEventArgs<DirectoryInfo>(new DirectoryInfo(dir)); DirectoryFound(this, args); } // do something with the directory... GetDirectories(dir, dirNode); } } private void GetFiles(string path) { foreach (string file in Directory.EnumerateFiles(path)) { if (FileFound != null) { IOEventArgs<FileInfo> args = new IOEventArgs<FileInfo>(new FileInfo(file)); FileFound(this, args); } // do something with the file... } }
上面的 cmets(“做某事 [...]”)是我可以将文件或目录添加到某些数据结构的位置。
进行此类搜索的最常见因素是处理时间,尤其是对于大型目录。所以很自然地,我想再向前迈出一步并实现线程。现在,我对线程的了解非常有限,但到目前为止,这是我想出的大纲:
public void Search()
{
m_searchThread = new Thread(new ThreadStart(SearchThread));
m_searching = true;
m_searchThread.Start();
}
private void SearchThread()
{
GetDirectories(m_path);
m_searching = false;
}
如果我使用此实现,则在控件中分配事件,它会抛出错误(如我所料),我的 GUI 应用程序正在尝试访问另一个线程。
任何人都可以对此实现以及如何完成线程提供反馈。谢谢。
更新(selkathguy 推荐):
这是根据 selkathguy 的建议调整后的代码:
private void GetDirectories(DirectoryInfo path)
{
GetFiles(path);
foreach (DirectoryInfo dir in path.GetDirectories())
{
if (DirectoryFound != null)
{
IOEventArgs<DirectoryInfo> args = new IOEventArgs<DirectoryInfo>(dir);
DirectoryFound(this, args);
}
// do something with the directory...
GetDirectories(dir);
}
}
private void GetFiles(DirectoryInfo path)
{
foreach (FileInfo file in path.GetFiles())
{
if (FileFound != null)
{
IOEventArgs<FileInfo> args = new IOEventArgs<FileInfo>(file);
FileFound(this, args);
}
// do something with the file...
}
}
原码耗时:47.87s
修改后的代码耗时:46.14s
【问题讨论】:
标签: c# multithreading recursion io