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
?
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
?
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.
Although the stack of the thread is claimed only when the thread actually starts, registering the thread for execution still takes some memory and thus can lead to an OutOfMemoryException.
I think you got something wrong. A thread DOES take memory in order to start. Every thread has its own stack
, own stackpointer
, etc. which memory must be reserved for. And if you happen not to have enough memory, an exception
will be thrown.