c# - 为什么 Thread.Start 会抛出 OutOfMemoryException

标签 c# .net

这个问题与我之前的问题有关 Thread overhead

既然 Thread.Start 没有为线程运行申请内存,为什么它会抛出 OutOfMemoryException

最佳答案

以下是在 CLR 中启动托管线程的部分源代码:

CExecutionEngine::SetupTLSForThread(pThread);
if (!pThread->InitThread(fInternal) ||
    !pThread->PrepareApartmentAndContext())
    ThrowOutOfMemory();
if (UnsafeTlsSetValue(gThreadTLSIndex, (VOID*)this) == 0)
{
    ThrowOutOfMemory();
}
if (UnsafeTlsSetValue(GetAppDomainTLSIndex(), (VOID*)m_pDomain) == 0)
{
    ThrowOutOfMemory();
}

在很多情况下,它确实会抛出内存不足;如果无法初始化线程,无法准备单元或上下文,或者无法分配线程本地存储,则抛出“内存不足”。

在我看来这是个坏主意;我更愿意为“我试图分配一个新的虚拟内存块,但找不到所需大小的 block ”的情况保留“内存不足”。由于没有可用的 TLS 插槽或线程初始化失败等原因而导致内存不足只会让人感到困惑。

关于c# - 为什么 Thread.Start 会抛出 OutOfMemoryException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15789507/

相关文章:

XML 序列化 "There is an error in XML document (2, 2)"的 C# 错误

c# - Visual Studio 不断用旧版本覆盖 NewtonSoft.Json.DLL

.net - 从文本框中删除文本

c# - HTTPS POST Web 服务请求格式 - 在子节点内插入多个值

c# - 是否可以在 .NET 中启动下载管理器(一个进程)

.net - 如何使用 RuntimeTypeModel 将 ProtoInclude 与 protobuf-net 中的类型关联起来?

c# - 重定向到 Jquery 中的 Action-Controller MVC 4

c# - 从 .NET 中的同一对话框中选择文件或文件夹

c# - C#中的异步图像处理

.net - 确定何时在(非托管)C++ 中加载 .NET