在向浏览器写入太多时,防止出现内存不足错误

JoJ*_*oJo 1 c# asp.net

我被分配了解决问题的任务,我怀疑有太多数据试图写入浏览器.即构建表以显示2,000多条记录.

$exception  {"Exception of type 'System.OutOfMemoryException' was thrown."} System.Exception {System.OutOfMemoryException}
Run Code Online (Sandbox Code Playgroud)

抛出异常 Page_PreRender

解决问题的最简单方法是什么?

测试/解决它的最简单方法是什么?

谢谢

[OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown.]
   System.String.Concat(String str0, String str1, String str2, String str3) +76
   ProgramName.File.GetData() in C:\inetpub\wwwroot\ProgramName\File.aspx.cs:137
   ProgramName.File.Page_PreRender(Object sender, EventArgs e) in C:\inetpub\wwwroot\ProgramName\File.aspx.cs:18
   System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +14
   System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +35
   System.Web.UI.Control.OnPreRender(EventArgs e) +8775110
   System.Web.UI.Control.PreRenderRecursiveInternal() +80
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +842
Run Code Online (Sandbox Code Playgroud)

RB.*_*RB. 6

随着堆栈跟踪,我想我知道你的问题.

在你的Page_PreRender方法中,你是连接字符串(你提到你正在构建一个表 - 它可能是代码执行此操作).

如果将两个字符串连接在一起,则会分配内存get来创建一个新字符串来保存结果,但是存储前两个字符串的内存不会被回收,因为这些字符串仍在范围内.我猜你正在连接很多字符串(在循环中),因此内存不足.

修复是使用StringBuilder.

找到看起来像这样的代码:

public void GetData() 
{
    string myTableString = "";
    foreach (var row in MyRows)
    {
        myTableString += "<tr><td>" + row.someProperty + "</td></tr>"
    }
Run Code Online (Sandbox Code Playgroud)

以下

using System.Text // This goes at the top of the file, with the other using statements.
...

public void GetData() 
{
    StringBuilder sb = new StringBuilder();
    foreach (var row in MyRows)
    {
        sb.Append("<tr><td>" + row.someProperty + "</td></tr>");
    }
    string myTableString = sb.ToString();
Run Code Online (Sandbox Code Playgroud)

请注意,上面给出的代码只是我对代码的最佳猜测 - 如果您发布代码会更容易!

  • 你我的朋友是天才!:) - 我猜这个名单变得太大了,因为最后一个人写了它并且它破了!谢谢! (2认同)