如何在c#.net中的同一个应用程序中使用多个线程池 [英] how to use multiple threadpool in same application in c#.net

查看:358
本文介绍了如何在c#.net中的同一个应用程序中使用多个线程池的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码。

here is my code .

private static void Main(string[] args)
  {

    for (int s = 0; s < NumThreads; s++)
    {
        ThreadPool.SetMaxThreads(5, 5);
     // ThreadPool.QueueUserWorkItem(new WaitCallback(DoWork), (object)s);
        ThreadPool.QueueUserWorkItem(new WaitCallback(ProcessData), (object)s);
    }

    Console.WriteLine("Waiting...");


    Thread.Sleep(1000*666);
    Console.WriteLine("And the answers are: ");

  }
  private static void ProcessData(object o)
  {
      Console.WriteLine("Input is " + (int)0);
      Thread.Sleep(1000 * 5);
  }









这里我使用线程池Threapool类。但我需要再创建一个最大线程为10的线程池。如何做到这一点。 b / c threapool是一个静态的。它可适用于孔应用。如何在c#





here i made a threadpool using Threapool class. but i need to create one more thread pool with max thread of 10. how to do that. b/c threapool is a static. it may applicable for hole applicaiton. how to create one more thread pool in c#

推荐答案

中创建一个以上的线程池?为什么?完全没有理由这样做!



多个线程池对彼此都不会有任何了解,因此只会相互踩一下,可能会使处理器饱和。



线程池只是一个准备运行的线程池,需要运行一些代码。该进程只能运行与其核心相同数量的线程,因此没有必要扩展线程池的数量。



如果池中有25个线程和一个四核处理器,任何时候只能运行4个线程!即使他们有工作要做,你的21个线程也处于空闲状态。添加另一个25个线程的池仍然只允许4个线程运行,但现在你已经有(21 + 25)个线程在等待做某事。



执行此操作的唯一方法是创建自己的线程池实现。真的,这不值得。
WHY? There's no reason to do that at all!

Multiple thread pools wouldn't know anything about each other and will therefor just step all over each other, probably saturating the processor.

A thread pool is just a pool of ready-to-run threads looking for some code to run. The process can only run the same number of threads that it has cores so there's no point to expanding the number of thread pools.

If you have 25 threads in the pool and a quad-core processor, only 4 threads can run at any one time! 21 of your threads are sitting idle, even if they have work to do. Adding another pool of 25 threads will still only allow 4 threads to run, but now you've got (21 + 25) threads sitting, waiting to do something.

The only way to do this would be to create your own thread pool implementation. Really, it's not worth it.


这篇关于如何在c#.net中的同一个应用程序中使用多个线程池的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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