【问题标题】:Separate threadPool for each task为每个任务单独的线程池
【发布时间】:2011-07-21 10:22:51
【问题描述】:

我的应用程序有两个主要任务:编码、处理视频。 这些任务是独立的。 我希望使用可配置的线程数运行的每个任务。 出于这个原因,对于一项任务,我通常使用 ThreadPool 和 SetMaxThreads。但是现在我有两个任务,并且想要“每个任务的两个可配置(线程数)线程池”。 好吧,ThreadPool 是一个静态类。那么我该如何实施我的策略(每个任务的线程数易于配置)。

谢谢

【问题讨论】:

    标签: c# multithreading threadpool


    【解决方案1】:

    您可能需要自己的线程池。如果您使用的是 .NET 4.0,那么如果您使用 BlockingCollection 类,则实际上很容易自行开发。

    public class CustomThreadPool
    {
      private BlockingCollection<Action> m_WorkItems = new BlockingCollection<Action>();
    
      public CustomThreadPool(int numberOfThreads)
      {
        for (int i = 0; i < numberOfThreads; i++)
        {
          var thread = new Thread(
            () =>
            {
              while (true)
              {
                Action action = m_WorkItems.Take();
                action();
              }
            });
          thread.IsBackground = true;
          thread.Start();
        }
      }
    
      public void QueueUserWorkItem(Action action)
      {
        m_WorkItems.Add(action);
      }
    }
    

    这就是它的全部内容。您将为要控制的每个实际池创建一个CustomThreadPool。我发布了最少的代码来获得一个粗略的线程池。当然,您可能希望调整和扩展此实现以满足您的特定需求。

    【讨论】:

      猜你喜欢
      • 2012-09-03
      • 1970-01-01
      • 2015-07-22
      • 2012-07-26
      • 1970-01-01
      • 2015-04-24
      • 2020-04-22
      • 2012-08-11
      • 2010-09-07
      相关资源
      最近更新 更多