gpt4 book ai didi

c# - 如何在完成之前访问 DirectoryInfo.EnumerateFiles

转载 作者:行者123 更新时间:2023-11-30 13:09:27 26 4
gpt4 key购买 nike

在我问的问题中Retrieve a list of filenames in folder and all subfolders quickly还有一些我发现的,似乎搜索许多文件的方法是使用 EnumerateFiles 方法。

The EnumerateFiles and GetFiles methods differ as follows: When you use EnumerateFiles, you can start enumerating the collection of names before the whole collection is returned; when you use GetFiles, you must wait for the whole array of names to be returned before you can access the array. Therefore, when you are working with many files and directories, EnumerateFiles can be more efficient.

这对我来说听起来很棒,我的搜索大约需要 10 秒,所以我可以在收到信息时开始制作我的列表。但我无法弄清楚。当我运行 EnumerateFiles 方法时,应用程序会卡住,直到它完成。我可以在后台工作程序中运行它,但同样的事情也会发生在那个线程上。有帮助吗?

 DirectoryInfo dir = new DirectoryInfo(MainFolder);
List<FileInfo> matches = new List<FileInfo>(dir.EnumerateFiles("*.docx",SearchOption.AllDirectories));

//This wont fire until after the entire collection is complete
DoSoemthingWhileWaiting();

最佳答案

您可以通过将其插入后台任务来完成此操作。

例如,你可以这样做:

var fileTask = Task.Factory.StartNew( () =>
{
DirectoryInfo dir = new DirectoryInfo(MainFolder);
return new List<FileInfo>(
dir.EnumerateFiles("*.docx",SearchOption.AllDirectories)
.Take(200) // In previous question, you mentioned only wanting 200 items
);
};

// To process items:
fileTask.ContinueWith( t =>
{
List<FileInfo> files = t.Result;

// Use the results...
foreach(var file in files)
{
this.listBox.Add(file); // Whatever you want here...
}
}, TaskScheduler.FromCurrentSynchronizationContext()); // Make sure this runs on the UI thread

DoSomethingWhileWaiting();

您在评论中提到:

I want to display them in a list. and perfect send them to the main ui as they come in

在这种情况下,您必须在后台处理它们,并在它们进入时将它们添加到列表中。类似于:

Task.Factory.StartNew( () =>
{
DirectoryInfo dir = new DirectoryInfo(MainFolder);
foreach(var tmp in dir.EnumerateFiles("*.docx",SearchOption.AllDirectories).Take(200))
{
string file = tmp; // Handle closure issue

// You may want to do this in batches of >1 item...
this.BeginInvoke( new Action(() =>
{
this.listBox.Add(file);
}));
}
});
DoSomethingWhileWaiting();

关于c# - 如何在完成之前访问 DirectoryInfo.EnumerateFiles,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10605659/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com