sing System;
using System.Collections.Generic;
using System.Text;
using System.Threading;namespace WZDM.Test
{
    /// <summary>
    /// 限制并发线程数例程
    /// </summary>
    public class TestThread 
    {
        int _currentThreads = 0;
        int _maxThreads = 10;        public void Test()
        {
            while (true)
            {
                //_maxThreads = new Random().Next(1, 10);
                for (int i=0; i<100; i++)
                {
                    // 在此进行数量限制
                    if (_currentThreads >= _maxThreads)
                        break;                    // 开启线程
                    lock (typeof(TestThread))
                    {
                        _currentThreads++;
                        if (_currentThreads > _maxThreads)
                            _currentThreads = _maxThreads;                        string currentInfo = string.Format("thread {0}/{1}", _currentThreads, _maxThreads);
                        Console.WriteLine(currentInfo + " start");
                        Thread thread = new Thread(new ParameterizedThreadStart(Run));
                        thread.Start(currentInfo);
                    }
                }                System.Threading.Thread.Sleep(2000);
            }
        }        // 线程任务
        void Run(object obj)
        {
            for (int i = 0; i < 100; i++)
            {
                Console.WriteLine("{0}:{1}", obj, i);
                Thread.Sleep(100);
            }
            Console.WriteLine("{0} finished", obj);
            lock (typeof(TestThread))
            {
                _currentThreads--;
                if (_currentThreads < 0)
                    _currentThreads = 0;
            }
        }
    }
}

解决方案 »

  1.   

     for (int i = 0; ; i++)  你牛啊
      

  2.   

    CLR对线程池有限制CLR1.x 30左右
    CLR2.0 具体不记得了,多了很多
    CLR4.0 不知道自建线程没限制
      

  3.   

    一个线程默认要保留1m的堆栈空间(用于局部变量,参数传递等)。
    32位操作系统中一个程序默认可分配最多2G的内存地址。不断的开线程,最终会导致内存地址用完并抛出OutOfMemoryException异常。你看到的“程序才吃到50M 左右”是该程序实际用到的内存,并不矛盾。
      

  4.   

    Win32单程序最大管理到2G内存
    线程2000个左右不虽然你看到占用只有50M,其实他占了虚拟内存2G了已经