c# - 更改容量时出现 StringBuilder 异常!

标签 c# .net exception memory stringbuilder

这是我的代码行:

StringBuilder myCompleteMessage = new StringBuilder();
myCompleteMessage.Capacity = Int32.MaxValue-1;

也试过:

myCompleteMessage.Capacity = myCompleteMessage.MaxCapacity-1;

我在第 2 行遇到异常。

Exception of type 'System.OutOfMemoryException' was thrown.

堆栈跟踪:

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)

最佳答案

假设您在 32 位系统上,第二行总是会失败。您要求 .NET 为您的 StringBuilder 分配 4 GB 的空间,这比进程必须使用的内存多(感谢 Joel 指出 char 占用 2 个字节,而不是 1 个字节)。

编辑
如果您使用 ILSpy 查看 StringBuilder,您会在 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;
}

通过将 Capacity 设置为 int.MaxValue - 1,您告诉 .NET 尝试分配一个 4 GB 的字符数组,这就是代码失败的原因。

关于c# - 更改容量时出现 StringBuilder 异常!,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6619182/

相关文章:

C#: 未找到方法异常(缺少 Setter)

exception - Ada 83 异常是否包括资源清理?

c# - 如何使用 OpenXml Wordprocessing 在表格中为每个新页面创建标题

c# - 抛出 VS 重新抛出 : same result?

c# - "Request.Cookies ("iduser "). Value"在 C# 中等效

c# - 加拿大邮政编码验证

c# - DDD - 实体状态转换

c# - catch 关键字如何确定抛出的异常类型?

c# - 是否可以使用 C# 检测 DTMF 音调

java - 多线程求和