OutOfMemoryException将StringBuilder的长度设置为0 [英] OutOfMemoryException setting StringBuilder length to 0

查看:217
本文介绍了OutOfMemoryException将StringBuilder的长度设置为0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将Stringbuilder的Length属性设置为0.之前,SB的长度为146,514,177.不过这是偶然的,我不应该例外.调用堆栈为:

I'm setting the Length property of a Stringbuilder to 0. Before, the SB's length is 146,514,177. That's by accident, though, I shouldn't get an exception. The callstack is:

   bei System.String.GetStringForStringBuilder(字符串值,Int32 startIndex,Int32长度,Int32容量)
   bei System.Text.StringBuilder.GetThreadSafeString(IntPtr& tid)
   bei System.Text.StringBuilder.set_Length(Int32值)

   bei System.String.GetStringForStringBuilder(String value, Int32 startIndex, Int32 length, Int32 capacity)
   bei System.Text.StringBuilder.GetThreadSafeString(IntPtr& tid)
   bei System.Text.StringBuilder.set_Length(Int32 value)

为什么要尝试获取字符串?这是一个32位进程,该进程的工作集大小为950 MB. (我知道32位进程的限制是2 GB).但是,将Length设置为0不应占用更多内存.为什么这是必需的?

Why is it trying to get the string? It's a 32 bit process and the process' working set size is 950 MB. (I know the limit is 2 GB for a 32 bit process). Though, setting Length=0 should not consume additional memory. Why is this necessary?

Armin

推荐答案

我尝试将此代码作为测试,但根本无法获得任何异常

I tried this code as a test and cannot get any exception at all

Public Class Form1
    Dim sb As New System.Text.StringBuilder
    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
        For i As Integer = 0 To 146514176
            sb.Append("X")
        Next
        MsgBox("done")
    End Sub

    Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
        MsgBox(sb.Length.ToString)
        'sb.Clear()
        sb.Length = 0
        MsgBox(sb.Length.ToString)
    End Sub
End Class

我多次尝试.clear和.length = 0-赢得7 32位VS 2010

I tried both .clear and .length = 0 many times - Win 7 32 bit VS 2010

我认为将长度设置为0或清除应该释放字符串构建器占用的任何内存.

I'd think setting the length to 0 or clearing should free up any memory occupied by the string builder.


这篇关于OutOfMemoryException将StringBuilder的长度设置为0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆