2012-01-08 87 views
1

問題是程序引發異常。創建多個線程後。我們如何限制在循環中創建的線程數量?OutOfMemoryException多線程c#

for (int jrCnt = rCnt; jrCnt <= arrayTable.GetUpperBound(0); jrCnt++) 
       { 
        /* bla bla bla */ 

        if ((!string.IsNullOrEmpty(prcI.name)) && 
         (prcI.prc != 0)) 
        { 
         /*bla bla bla*/ 

         var thread = // run updade or add 
                new Thread(() => 
                { 

                 if (!Accessor.AddProductUpdateProduct(prcI)) _updateCounter++; 
                 _countadd++; 

                }); 
         thread.Name = "Add_or_update-no_" + thread.ManagedThreadId; 
         thread.Priority = ThreadPriority.Lowest; 

         thread.Start(); 
        } 

一些說明。

這裏是循環開始前n次。一旦我添加了線程池,這個循環非常快。因此Threadpool觸發了180次。我爲我的英語道歉。

for (int i = sbook; i < book; i++) 
      { 
       dt = Accessor.ImporterXls(_path, i);// array for method 

       ConstructWithBook(dt, rCnt, sbook, book, priceSelect, nametov, pricetov, 
           categorytov); 
      } 
+0

你需要在這裏提供一些背景和更具體的字你的問題。現在直接回答你的問題,我會說刪除Thread.Start .. – diggingforfire 2012-01-08 04:31:37

+0

我想要一段代碼在一個單獨的線程中執行。我需要它來加速該計劃。這個循環處理9000條記錄。因此,創建大量的線程和沒有足夠的內存。 – JinDeveloper 2012-01-08 04:54:42

回答

1
+0

使用線程池。但是這個週期是快節奏的,並且從9000處理了180條記錄。 – JinDeveloper 2012-01-08 04:50:31

+0

這就是你的問題的根源,你超出了可用的系統資源。線程池應該更高效,因爲您不創建新線程。嘗試查看[GetMaxThreads](http://msdn.microsoft.com/zh-cn/library/system.threading.threadpool.getmaxthreads.aspx)和[SetMaxThreads](http://msdn.microsoft.com/zh-cn/ -us/library/system.threading.threadpool.setmaxthreads.aspx)方法 – 2012-01-08 04:54:10

+0

我添加了導致此問題的代碼。感謝您的幫助! – JinDeveloper 2012-01-08 05:07:23