簡體   English   中英

在 C# 中運行 200 個線程的最佳方式

[英]The best way to run 200 threads in C#

以前,我使用了以下代碼:

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 秒的工作,幾乎無限次,有時運行線程的數量會發生變化。 如何在不泄漏內存且不損失性能的情況下完成此操作。

生成一個隊列並擁有與處理器數量一樣多的線程。 然后讓線程從隊列中讀取並處理消息。 不要破壞線程,讓它們無限期地運行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM