StringBuilder.ToString()抛出OutOfMemoryException [英] StringBuilder.ToString() throws OutOfMemoryException

查看:498
本文介绍了StringBuilder.ToString()抛出OutOfMemoryException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试使用 ToString() StringBuilder $ c>方法将引发 OutOfMemoryException

I have a created a StringBuilder of length "132370292", when I try to get the string using the ToString() method it throws OutOfMemoryException.

StringBuilder SB = new StringBuilder();

for(int i =0; i<=5000; i++)
{
    SB.Append("Some Junk Data for testing. My Actual Data is created from different sources by Appending to the String Builder.");
}

try
{
    string str = SB.ToString(); // Throws OOM mostly
    Console.WriteLine("String Created Successfully");
}
catch(OutOfMemoryException ex)
{
    StreamWriter sw = new StreamWriter(@"c:\memo.txt", true);
    sw.Write(SB.ToString()); //Always writes to the file without any error
    Console.WriteLine("Written to File Successfully");
}

创建新字符串时OOM的原因是什么,为什么不这样做

What is the reason for the OOM while creating a new string and why it doesn't throw OOM while writing to a file?

机器详细信息:64位,Windows-7、2GB RAM,.NET版本2.0

Machine Details: 64-bit, Windows-7, 2GB RAM, .NET version 2.0

推荐答案


在创建新字符串时OOM是什么原因

What is the reason for the OOM while creating a new string

因为您的内存不足-或至少,CLR无法分配具有您要求的大小的对象。真的就是这么简单。如果您想避免这些错误,请不要尝试创建不适合内存的字符串。请注意,即使您有很多内存,并且即使您正在运行64位CLR,也可以创建的对象大小受到限制。

Because you're running out of memory - or at least, the CLR can't allocate an object with the size you've requested. It's really that simple. If you want to avoid the errors, don't try to create strings that don't fit into memory. Note that even if you have a lot of memory, and even if you're running a 64-bit CLR, there are limits to the size of objects that can be created.

以及为什么在写入文件时不抛出OOM?

and why it doesn't throw OOM while writing to a file ?

因为您有更多磁盘空间大于内存。

Because you have more disk space than memory.

我很确定代码不是与您所描述的完全相同。该行将无法编译:

I'm pretty sure the code isn't exactly as you're describing though. This line would fail to compile:

sw.write(SB.ToString());

...因为方法是写入而不是。如果您实际上是在 调用 SB.ToString(),那么失败的可能性就和 str = SB一样.ToString()

... because the method is Write rather than write. And if you're actually calling SB.ToString(), then that's just as likely to fail as str = SB.ToString().

您似乎很有可能实际上是在流式写入文件时尚,例如

It seems more likely that you're actually writing to the file in a streaming fashion, e.g.

using (var writer = File.CreateText(...))
{
    for (int i = 0; i < 5000; i++)
    {
        writer.Write(mytext);
    }
}

这样,您永远不需要大量的文本在内存中-它只是将其写入磁盘,可能有 some 缓冲,但不足以引起内存问题。

That way you never need to have huge amounts of text in memory - it just writes it to disk as it goes, possibly with some buffering, but not enough to cause memory issues.

这篇关于StringBuilder.ToString()抛出OutOfMemoryException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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