C# 在C中运行200个线程的最佳方法#

C# 在C中运行200个线程的最佳方法#,c#,multithreading,C#,Multithreading,之前,我使用了以下代码: 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 } } for(i

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

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
    }
}
for(int i=0;i
它工作正常,但在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();
            }
        }
}
classthreadspool
{
私有静态int-maxThreads=0;
私有静态线程[]threadsArray;
私有静态int-activeThread=0;
公共静态无效初始值设定项(int-maxThreads)
{
ThreadsPool.maxThreads=maxThreads;
对于(int i=0;i
但问题是这个类会造成内存泄漏。
你是否意识到我必须做10秒的工作,几乎无限次,有时运行线程的数量会发生变化。如何做到这一点而不造成内存泄漏和性能损失。

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

首先,你在做什么,你需要多达200个线程?我认为这是一个设计问题。如果您有200个线程在运行,那么您总是会遇到性能问题。没有Prozessor可以快速处理这个问题。我需要处理图像。我知道200条线不是不可能的。不要打断200条线。将线程数拆分为CPU核心数。您可能需要一个线程池吗?默认情况下,TPL(
Parallel.For
)和PLINQ(
enumerable.AsParallel()
)框架将使用适当数量的线程(我认为是逻辑核心数*2)来处理数据。