【问题标题】:The best way to run 200 threads in C#在 C# 中运行 200 个线程的最佳方法
【发布时间】:2016-10-23 15:12:36
【问题描述】:

之前,我使用了以下代码:

for (int i = 0; i < config.threads; i++)
{
  Thread thread = new Thread(workThread);
  thread.IsBackground = true;
  thread.Start();
}

public static void workThread()
{
    while (true)
    {
        // work, 10 second
    }
}

它工作正常,但在 10-15 个周期后,开始工作较少。然后我写了一个类来创建单独的线程:

class ThreadsPool
{
    private static int maxThreads = 0;
    private static Thread[] threadsArray;
    private static int activeThread = 0;


    public static void Initializer(int maxThreads)
    {
        ThreadsPool.maxThreads = maxThreads;
        for (int i = 0; i < maxThreads; i++)
        {
            Thread thread = new Thread(Program.workThread);
            thread.IsBackground = true;
            thread.Start();
        }
        Thread threadDaemon = new Thread(Daemon);
        threadDaemon.IsBackground = true;
        threadDaemon.Start();
    }

    public static void activeThreadMinus()
    {
        Interlocked.Decrement(ref activeThread);
    }

    private static void Daemon()
    {
        while(true)
        {
            if(activeThread < maxThreads)
            {
                Thread thread = new Thread(Program.workThread);
                thread.IsBackground = true;
                thread.Start();
            }
            Thread.Sleep(5);
        }
    }

public static void workThread()
       {
            while (true)
            {
                // work 10 sec
                ThreadsPool.activeThreadMinus();
            }
        }
}

但问题是这个类会造成内存泄漏。 你是否意识到我必须做 10 秒的工作,几乎无限次,有时运行线程的数量会发生变化。如何在没有内存泄漏和性能损失的情况下做到这一点。

【问题讨论】:

  • 起初你在做什么,你需要多达 200 个线程?我认为这是一个设计问题。如果你有 200 个线程在运行,你总是会遇到性能问题。没有任何 Prozessor 可以快速处理这个问题。
  • 我需要处理图像。我知道线程 200 并非不可能。
  • 不要闯入200个线程。分解成线程数等于CPU核心数。
  • 可能你需要一个线程池来代替?
  • 默认情况下,TPL (Parallel.For) 和 PLINQ (enumerable.AsParallel()) 框架将使用适当数量的线程处理您的数据(我认为这是逻辑核心数 * 2)。

标签: c# multithreading


【解决方案1】:

生成一个队列并拥有与处理器数量一样多的线程。然后让线程从队列中读取并处理消息。不要破坏线程,让它们无限期地运行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-02
    • 1970-01-01
    • 1970-01-01
    • 2011-12-03
    • 2023-03-21
    • 1970-01-01
    • 1970-01-01
    • 2014-07-13
    相关资源
    最近更新 更多