Maximum number of threads in a .NET app?

前端 未结 7 2047
小蘑菇
小蘑菇 2020-11-22 17:43

What is the maximum number of threads you can create in a C# application? And what happens when you reach this limit? Is an exception of some kind thrown?

7条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-22 17:56

    Mitch is right. It depends on resources (memory).

    Although Raymond's article is dedicated to Windows threads, not to C# threads, the logic applies the same (C# threads are mapped to Windows threads).

    However, as we are in C#, if we want to be completely precise, we need to distinguish between "started" and "non started" threads. Only started threads actually reserve stack space (as we could expect). Non started threads only allocate the information required by a thread object (you can use reflector if interested in the actual members).

    You can actually test it for yourself, compare:

        static void DummyCall()
        {
            Thread.Sleep(1000000000);
        }
    
        static void Main(string[] args)
        {
            int count = 0;
            var threadList = new List();
            try
            {
                while (true)
                {
                    Thread newThread = new Thread(new ThreadStart(DummyCall), 1024);
                    newThread.Start();
                    threadList.Add(newThread);
                    count++;
                }
            }
            catch (Exception ex)
            {
            }
        }
    

    with:

       static void DummyCall()
        {
            Thread.Sleep(1000000000);
        }
    
        static void Main(string[] args)
        {
            int count = 0;
            var threadList = new List();
            try
            {
                while (true)
                {
                    Thread newThread = new Thread(new ThreadStart(DummyCall), 1024);
                    threadList.Add(newThread);
                    count++;
                }
            }
            catch (Exception ex)
            {
            }
        }
    

    Put a breakpoint in the exception (out of memory, of course) in VS to see the value of counter. There is a very significant difference, of course.

提交回复
热议问题