我正在使用以下代码测试在出现问题之前我的计算机可以处理多少线程:
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);
}
当系统无法创建更多线程时,我预计 new Thread(...)
构造函数会抛出异常(可能是 OutOfMemoryException
),但相反构造函数挂起并且永远不会返回。
而不是上面的输出
...
mspa 67
m
Got exception of type OutOfMemoryException
这是相当
...
mspa 67
m <- it hangs while 'm'aking the thread
那么,TLDR:为什么 new Thread(...)
在线程过多时挂起而不是抛出异常?
最佳答案
thread.Suspend();
那是一种邪恶、邪恶、邪恶的方法。在 .NET 2.0 版中强烈反对,目前还不清楚您是如何通过 [Obsolete] 消息而不注意到这一点的。我将引用有关此方法的 MSDN 注释:
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.
是的,这就是死锁的样子。
关于c# - 为什么在 C# 中创建一个新线程会挂起?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21384218/