除了@Jeroen 的出色回答之外,这不仅仅是线程方面的考虑。这是为了防止有人故意创建竞争条件并以这种方式导致缓冲区溢出。稍后在代码中,检查该局部变量的长度。如果代码要检查可访问变量的长度,则它可能在检查和wstrcpy
调用时间长度之间的不同线程上发生了变化:
// Check that we will not overrun our boundaries.
if ((uint)(chunkLength + chunkOffset) <= ret.Length && (uint)chunkLength <= (uint)sourceArray.Length)
{
///
/// imagine that another thread has changed the chunk.m_ChunkChars array here!
/// we're now in big trouble, our attempt to prevent a buffer overflow has been thawrted!
/// oh wait, we're ok, because we're using a local variable that the other thread can't access anyway.
fixed (char* sourcePtr = sourceArray)
string.wstrcpy(destinationPtr + chunkOffset, sourcePtr, chunkLength);
}
else
{
throw new ArgumentOutOfRangeException("chunkLength", Environment.GetResourceString("ArgumentOutOfRange_Index"));
}
}
chunk = chunk.m_ChunkPrevious;
} while (chunk != null);
不过真的很有趣的问题。