-3
以前,我用下面的代碼:的最佳方式在C#中運行200個線程
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可以快速處理這個問題。 – Sebi
我需要處理圖像。我知道線程200並非不可能。 – SavaLLL
不要分成200個線程。分解成等於CPU核心數的線程數。 –