且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用C#在循环中线程池

更新时间:2022-05-01 23:01:05

您当前的代码可以出问题的时候2以下的组合成立:

Your current code could go wrong when a combination of the 2 following holds:


  • 有非常多的文件

  • 处理一个文件(DoStuff)花费的时间显著金额

的线程池具有足够的负载平衡能力,并会继续产生越来越多的线程,远远超出***数目。

The Threadpool has insufficient load-balancing capabilities and would keep creating more and more threads, way beyond the optimal number.

如果你可以用FX4,使用TPL。

If you can use Fx4, use the TPL.

有关早期版本,重写代码以使用较少的线程。

For earlier versions, rewrite your code to use fewer threads.

您最大的收获可能是使用 System.Directory.EnumFiles()来代替 Directory.GetFiles()

Your biggest gain could be from using System.Directory.EnumFiles() to replace Directory.GetFiles().

素描:

var files = System.Directory.EnumerateFiles(...);  // deferred execution

Parallel.ForEach(files, f => DoStuff(f));  // maybe use MaxDegree or CancelationToken

// all files done here



你也可以把这个包.ForEach在(单)的try / catch等。

You can also wrap this .ForEach in a (single) try/catch etc.

如果 DoStuff()需要并行你应该使用TPL还有,沿的CancellationToken也许传递等,这将会把所有的并行单一调度的控制之下。

And if DoStuff() needs parallelism you should use the TPL as well, maybe passing along a CancellationToken etc. It would put all the Parallelism under the control of a single scheduler.

您可能需要协助微调,但同样会比没有TPL容易得多。

You might have to assist in fine-tuning but that too will be a lot easier than without the TPL.