使用C#在循环中线程池 [英] Using ThreadPool within loops in C#

查看:596
本文介绍了使用C#在循环中线程池的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不太避让了线程,但下面的代码可以接受的(我更担心的是使用一个循环内的线程池):

I'm not too clued up with threading but is the following code acceptable (I'm more worried about using thread pools within a loop):

      string[] filePaths = GetFilePaths();

      foreach (string filePath in filePaths )
      {
        ThreadPool.QueueUserWorkItem(DoStuff, filePath); 
      }



有没有其他办法,这可怎么办?

Is there any other way that this can be done?

编辑:

NB DoStuff的每次执行将依次创建多个线程分(约200)。这些子线程模拟系统的用户,仅用于接收和发送通过TCP的信息负责。

N.B. Each execution of DoStuff will in turn create multiple sub threads (about 200). These sub-threads simulate users of the system and is only responsible for receiving and sending information via TCP.

推荐答案

您当前的代码可以出问题的时候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.

这篇关于使用C#在循环中线程池的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆