c# - 为什么在 C# 中创建一个新线程会挂起?

标签 c# multithreading

我正在使用以下代码测试在出现问题之前我的计算机可以处理多少线程:

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/

相关文章:

c# - 没有默认值的枚举的 XML 序列化

c# - Asp.net mvc3 定期刷新结果而不重新加载页面

c# - Asp.net MVC 下拉列表中的多个字段

c++ - 如果 atomic_flag 变量是类的成员,我该如何初始化它?

C++回调定时器实现

c# - Visual Studio C# 项目中的自定义生成操作属性

multithreading - 在 BDB 中并行查找多个文件的值

c# - 计时器线程是等到回调函数中的所有步骤都完成还是回调函数在每个周期都被重新调用

python - Python 3.7 和 3.8 之间 Python thread.join() 的差异

c# - 应用程序因进程退出事件而退出