2012-01-08 38 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