简体   繁体   English

在使用Directory.GetFiles()的C#中,有没有一种方法可以在找到文件时启动线程,而不必等待?

[英]In C# Using Directory.GetFiles(), is there a way to start threads as files are found instead of having to wait?

In C# Using Directory.GetFiles(), is there a way to start threads as files are found? 在C#中使用Directory.GetFiles(),有没有一种方法可以在找到文件时启动线程?

The behavior appears to be 'find all the files' then do what you need on each. 行为似乎是“查找所有文件”,然后对每个文件执行所需的操作。 Is there another class that allows one to start threads (up to a certain count) as files are found? 是否存在另一类,当发现文件时,该类允许一个人启动线程(达到一定数量)?

You need to call Directory.EnumerateFiles , which is new to .Net 4.0. 您需要调用.Net 4.0新增的Directory.EnumerateFiles

This method returns a lazy enumerable; 此方法返回一个惰性枚举; each time you call MoveNext() , it will query the filesystem for the next file. 每次调用MoveNext() ,它将在文件系统中查询下一个文件。

You can start your threads like this: 您可以像这样启动线程:

foreach(var dontUse in Directory.EnumerateFiles(...)) {
    string path = dontUse;  //Create a new variable for each closure
    ThreadPool.QueueUserWorkItem(delegate {
        ...
    });
}

The temporary variable is necessary to ensure that each delegate closure references a separate variable; 临时变量对于确保每个委托闭包引用一个单独的变量是必不可少的; otherwise, they would all share the same value, causing trouble. 否则,它们将共享相同的值,从而造成麻烦。

SLaks has answered this for .NET 4.0. SLaks已针对.NET 4.0回答了这一问题。 Buf if you absolutely need this behavior in a pre-4.0 project, you can of course always do a PInvoke, using FindFirstFile and FindNextFile. 如果您在4.0之前的项目中绝对需要此行为,则当然可以始终使用FindFirstFile和FindNextFile进行PInvoke。 They return after each file (as the names imply). 它们在每个文件之后返回(顾名思义)。

There is an example on pinvoke.net. pinvoke.net上有一个示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM