@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);
しかし、本当に興味深い質問です。