Why does making a new Thread hang in C#?

c#, multithreading

Solution

   thread.Suspend();

That's an evil, evil, evil method. Strongly deprecated in .NET version 2.0, it isn't very clear how you got past the [Obsolete] message and not notice this. I'll quote the MSDN note about this method:

Do not use the Suspend and Resume methods to synchronize the activities of threads. You have no way of knowing what code a thread is executing when you suspend it. If you suspend a thread while it holds locks during a security permission evaluation, other threads in the AppDomain might be blocked. If you suspend a thread while it is executing a class constructor, other threads in the AppDomain that attempt to use that class are blocked. Deadlocks can occur very easily.

Yup, that's what a deadlock looks like.

Problem

I was testing how many threads my computer can handle before something goes wrong, using the following code: ``` static void Main(string[] args) { List<Thread> threads = new List<Thread>(); int count = 0; try { while (true) { Console.Write('m'); // make Thread thread = new Thread(() => { Thread.Sleep(Timeout.Infinite); }, 1024 * 64); Console.Write('s'); // start thread.Start(); Console.Write('p'); // suspend thread.Suspend(); Console.Write('a'); // add threads.Add(thread); Console.Write(' '); Console.WriteLine(count++); } } catch (Exception e) { Console.WriteLine("\nGot exception of type " + e.GetType().Name); } Console.WriteLine(count); Console.ReadKey(true); } ``` I was expected the `new Thread(...)` constructor to throw an exception (maybe `OutOfMemoryException`) when the system could not make any more threads, but instead the constructor hangs and never returns. Instead of the output from the above being ``` ... mspa 67 m Got exception of type OutOfMemoryException ``` it is rather ``` ... mspa 67 m <- it hangs while 'm'aking the thread ``` So, the TLDR: why does `new Thread(...)` hang instead of throw an exception when there are too many threads?

Original source