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

标签 c# winforms io .net

在我问的问题中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/

相关文章:

c# - 如何使用元数据类验证数据注释

c# - 从 IEnumerable 获取非不同元素

c# - 使用 BackGroundWorker 运行 WatiN 打开 IE 浏览器

c# - 显示标签文本 10 秒

c# - 无法在我的代码中使用 Hwndsource

c# - EF Changetracker 能否告诉您集合是否最初已填充?

c# - 为什么 ListView 拒绝显示其列、项目和子项目(仅显示组)?

UNIX 缓冲与非缓冲 I/O

Haskell primPutChar 定义

c++ - 为什么 fseek 不起作用?