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();
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。