簡體   English   中英

C#ThreadPool-OutOfMemoryException

[英]C# ThreadPool - OutOfMemoryException

我第一次為項目弄亂ThreadPools,並且需要能夠在main方法的兩個不同部分中對工作項進行排隊。 我做了一個簡單的示例進行測試,並在對象創建行的for循環中不斷獲取OutOfMemoryException。 為了釋放該線程占用的任何內存,我需要在線程執行結束時執行某種清理嗎? 如果沒有,我該如何解決內存問題?

class Program
{
    public static HashSet<String> domains;
    static void Main(string[] args)
    {
        //Static DB Connection
        //Database Set
        domains = new HashSet<string>();
        while (true)
        {
            //Pull Data From The Database
            String[] chars = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l" };
            for (int i = 0; i < 10; i++)
            {
                Loader l = new Loader(chars[i]);
                if (!domains.Contains(chars[i]))
                {
                    lock (domains)
                    {
                        domains.Add(chars[i]);
                    }
                    ThreadPool.QueueUserWorkItem(new WaitCallback(l.ThreadPoolCallback), i);
                }

            }
           for (int i = 0; i < 10; i++)
            {
                Parser p = new Parser();
                ThreadPool.QueueUserWorkItem(new WaitCallback(p.ThreadPoolCallback), i);
            }
        }
    }
}

解析器類:

 class Parser
{
    public void ThreadPoolCallback(Object threadContext)
    {
        ManualResetEvent eventx = new ManualResetEvent(false);
        //int threadIndex = (int)threadContext;
        Console.WriteLine("Parser Thread: " + threadContext);
        eventx.Set();
    }
}

裝載機類別:

class Loader
{
    String ch { set; get; }
    public Loader(String new_ch)
    {
        ch = new_ch;
    }
    public void ThreadPoolCallback(Object threadContext)
    {
        ManualResetEvent eventx = new ManualResetEvent(false);
        Console.WriteLine("Added " + this.ch + " to " + Thread.CurrentThread.GetHashCode());
        //int threadIndex = (int) threadContext;
        //Console.WriteLine("Loader Thread: " + threadContext + " " + ch + "  " + Thread.CurrentThread.GetHashCode());
        lock(Program.domains)
        {
            Program.domains.Remove(this.ch);
            Console.WriteLine("Removed " + this.ch + " from " + Thread.CurrentThread.GetHashCode());
        }
        eventx.Set();
    }

}

謝謝你

編輯感謝您的所有幫助。 我現在看到自己犯的錯誤

您有一個無限的while循環,除了吐出新線程外什么也不做。 線程占用大量內存(32位為1MB; 64位為4MB),因此如果您不先耗盡線程限制,最終將耗盡內存。

另外-您對ManualResetEvent的使用不正確。 需要在方法范圍之外創建它,否則它什么都不做(因為進入該方法的每個線程都將創建一個resetevent對象的新實例;為了進行同步,線程必須訪問同一對象)。

盡管線程池限制了線程數,但是您的循環並沒有限制隊列中用戶工作項的數量。 您的無限循環將耗盡mem。

就像羅肯所說的,兩線之間的一切

while(true)
{
   ....
}

正在無限地重復。

暫無
暫無

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

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