Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Thread.Start can throw OutOfMemoryException

Tags:

c#

.net

This question is related with my previous question Thread overhead

Since Thread.Start doesn't claim memory for the thread to run, why it can throw OutOfMemoryException?

like image 351
albert Avatar asked Apr 03 '13 14:04

albert


People also ask

What causes OutOfMemoryException?

When data structures or data sets that reside in memory become so large that the common language runtime is unable to allocate enough contiguous memory for them, an OutOfMemoryException exception results.

How do you fix system OutOfMemoryException exception of type system OutOfMemoryException was thrown?

OutOfMemoryException' was thrown. To resolve this issue, I had to restart Visual Studio or go to the Windows Task Manager and terminate IIS Express process. This error could happen due to a variety of reasons related to memory consumption of the application.


1 Answers

Here's part of the source code for starting up a managed thread in the 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();
}

Sure looks like it can throw out of memory in a number of situations; if the thread cannot be initialized, if the apartment or context cannot be prepared, or if the thread local storage cannot be allocated, then "out of memory" is thrown.

In my opinion this is a bad idea; I would prefer "out of memory" to be reserved for the situation of "I tried to allocate a new block of virtual memory and I couldn't find a block of the needed size." Throwing out of memory for things like there being no TLS slots available or thread initialization failing is just confusing.

like image 157
Eric Lippert Avatar answered Oct 13 '22 19:10

Eric Lippert