现象:

内存是绝对没有问题的,3g内存,发生异常时,任务管理器里显示,可用内存还有1G多!不知道什么原因!

int i=0;
while ((i++) < 2000)
            {
                try
                {
                    Thread t = new Thread(Test);
                    t.IsBackground = true;
                    t.Start();
                }
                catch (Exception ex)
                {
                    MessageBox.Show("current loop: " + i.ToString() + "\r\n" + ex.ToString());
                    break;
                }
            }

void Test()
        {
            Thread.Sleep(120 * 1000);
        }

  当线程加到1305时就会报OutOfMemoryException异常。

解决:

 .net默认为每个线程分配的椎大小是1m,当启动1305个线程时,光是启动线程就占用1305*1m的内存

//把椎大小由1m改为512K
Thread t = new Thread(Test, 1024 * 512);
                    t.IsBackground = true;
                    t.Start();

  

经过上面改动后,可以启动2602个线程.

 

相关文章:

  • 2021-12-04
  • 2021-12-03
  • 2022-12-23
  • 2021-11-20
  • 2021-11-20
  • 2021-10-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-06-16
  • 2021-05-18
  • 2022-12-23
  • 2021-05-19
  • 2021-10-05
  • 2022-01-01
相关资源
相似解决方案