加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 20:00:21 所属栏目:百科 来源:网络整理
导读:在问我 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
在问我 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();

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读