C# Stringbuilder 在添加大量文本时损坏内容
C# Stringbuilder corrupting content when adding lots of text
我 运行 遇到了 stringbuilder 的问题,我似乎无法解决。为了简化问题,我创建了以下方法:
private static string TestBigStrings() {
StringBuilder builder = new StringBuilder();
for (int i = 1; i < 1500; i++) {
string line = "This is a line isn't too big but breaks when we add to many of it.";
builder.AppendLine(line);
}
return builder.ToString();
}
它应该只是将该行添加 1500 次,然后将它组合成一个字符串并 return 它。然而,不仅仅是组合它会破坏内容。在结果中间的某个地方,您会找到文本:
This is a line isn't too big but breaks when we add to many of it.
This is a line isn't too big but breaks when we add to many of it.
This is a line isn't too big but breaks when we add to many of it.
This is a line isn't too big but breaks when we add to many of ...s a line isn't too big but breaks when we add to many of it.
This is a line isn't too big but breaks when we add to many of it.
This is a line isn't too big but breaks when we add to many of it.
This is a line isn't too big but breaks when we add to many of it.
该项目是一个简单的控制台。我还尝试了所有其他解决方案来检查这是否可行,例如:
正在将文本写入文件(同样的损坏并提前中断)
将其写入内存流并读取(同样的损坏)
使用列表并加入该列表(同样损坏)
仅在字符串上使用 +=(同样损坏)
使用 string.concat(同样的损坏)
我问过的所有同事都运行遇到同样的问题,所以它应该与 PC 无关。有人知道这里发生了什么吗?
这是您遇到的情况吗?
嗯,这只是调试器在骗你。它会缩短太长的字符串以避免过多的内存使用。
我将该字符串写入一个文件,用一个简单的:
File.WriteAllText("BigString.txt", str);
猜猜看:字符串如预期的那样在那里,并且没有以任何方式损坏。
我 运行 遇到了 stringbuilder 的问题,我似乎无法解决。为了简化问题,我创建了以下方法:
private static string TestBigStrings() {
StringBuilder builder = new StringBuilder();
for (int i = 1; i < 1500; i++) {
string line = "This is a line isn't too big but breaks when we add to many of it.";
builder.AppendLine(line);
}
return builder.ToString();
}
它应该只是将该行添加 1500 次,然后将它组合成一个字符串并 return 它。然而,不仅仅是组合它会破坏内容。在结果中间的某个地方,您会找到文本:
This is a line isn't too big but breaks when we add to many of it.
This is a line isn't too big but breaks when we add to many of it.
This is a line isn't too big but breaks when we add to many of it.
This is a line isn't too big but breaks when we add to many of ...s a line isn't too big but breaks when we add to many of it.
This is a line isn't too big but breaks when we add to many of it.
This is a line isn't too big but breaks when we add to many of it.
This is a line isn't too big but breaks when we add to many of it.
该项目是一个简单的控制台。我还尝试了所有其他解决方案来检查这是否可行,例如:
正在将文本写入文件(同样的损坏并提前中断)
将其写入内存流并读取(同样的损坏)
使用列表并加入该列表(同样损坏)
仅在字符串上使用 +=(同样损坏)
使用 string.concat(同样的损坏)
我问过的所有同事都运行遇到同样的问题,所以它应该与 PC 无关。有人知道这里发生了什么吗?
这是您遇到的情况吗?
嗯,这只是调试器在骗你。它会缩短太长的字符串以避免过多的内存使用。
我将该字符串写入一个文件,用一个简单的:
File.WriteAllText("BigString.txt", str);
猜猜看:字符串如预期的那样在那里,并且没有以任何方式损坏。