Dan*_*npe 3 .net c# memory stringbuilder exception
这是我的代码行:
StringBuilder myCompleteMessage = new StringBuilder();
myCompleteMessage.Capacity = Int32.MaxValue-1;
Run Code Online (Sandbox Code Playgroud)
尝试过:
myCompleteMessage.Capacity = myCompleteMessage.MaxCapacity-1;
Run Code Online (Sandbox Code Playgroud)
我在第2行得到例外.
Exception of type 'System.OutOfMemoryException' was thrown.
Run Code Online (Sandbox Code Playgroud)
堆栈跟踪:
at System.String.GetStringForStringBuilder(String value, Int32 startIndex, Int32 length, Int32 capacity)
at System.Text.StringBuilder.set_Capacity(Int32 value)
at Orca.Server.HandleClientComm(Object newClient) in C:\Users\Dan\Documents\Visual Studio 2010\Projects\msig\Orca\Server.cs:line 100
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart(Object obj)
Run Code Online (Sandbox Code Playgroud)
假设您使用的是32位系统,那么第二行将始终失败.你要求.NET为你的StringBuilder分配4 GB的空间,这比进程必须使用的内存更多(感谢Joel指出char占用2个字节,而不是1).
编辑
如果您查看StringBuilderILSpy,您会在集合中看到以下代码Capacity:
if (this.Capacity != value)
{
int num = value - this.m_ChunkOffset;
char[] array = new char[num];
Array.Copy(this.m_ChunkChars, array, this.m_ChunkLength);
this.m_ChunkChars = array;
}
Run Code Online (Sandbox Code Playgroud)
通过将Capacity设置为int.MaxValue - 1,您告诉.NET尝试分配4 GB字符数组,这就是代码失败的原因.