更改容量时StringBuilder异常!

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)

rsb*_*rro 8

假设您使用的是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字符数组,这就是代码失败的原因.

  • 不要忘记`char`是16位Unicode.容量1000是2000字节.@Adam,`int.MaxValue`是唯一明智的答案,因为`Capacity`是`int`.任何较小的"MaxCapacity"都是不必要的任意,因为该类无论如何都受到内存的限制.如果你有一台6-8GB或更多内存的机器,我相信你可以将"容量"设置为"MaxCapacity"就好了,因为它可能会使用4GB. (2认同)