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 completeDoSoemthingWhileWaiting();解决方法 您可以通过将其推送到后台任务来完成此 *** 作.
例如,您可以这样做:
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 threadDoSomethingWhileWaiting();
你在评论中提到:
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全部内容,希望文章能够帮你解决c# – 如何在完成之前访问DirectoryInfo.EnumerateFiles所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)