【问题标题】:C# out of memory errorC#内存不足错误
【发布时间】:2026-01-15 14:10:01
【问题描述】:

我已经尝试了几个小时来解决这个问题。当它执行时,它将一直运行,直到系统内存不足。 我尝试处理使用后创建的 bmp,它没有任何区别。 我也尝试过处理网络浏览器,但随后我需要在具有正确高度/宽度等的循环上运行网页以捕获它。 我尝试创建一个新的网络浏览器,它循环然后处理的所有内容,但它不会工作。 谁能看到这里可能发生了什么?

循环:

        wbcondor1.AllowNavigation = true;
        wbcondor1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(wbcondor1_DocumentCompleted);
        wbcondor1.Navigate("blanked out");

文档完成

  private void wbcondor1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
    {
        Bitmap condor1bmp = new Bitmap(600, 1000);
        wbcondor1.DrawToBitmap(condor1bmp, new Rectangle(wbcondor1.Location.X, wbcondor1.Location.Y, wbcondor1.Width, wbcondor1.Height));

        if (Convert.ToString(condor1bmp.GetPixel(553, 558)) == "Color [A=255, R=232, G=30, B=48]") { c1to1.Text = "lower"; }
        if (Convert.ToString(condor1bmp.GetPixel(553, 584)) == "Color [A=255, R=232, G=30, B=48]") { c1to2.Text = "lower"; }
        if (Convert.ToString(condor1bmp.GetPixel(553, 608)) == "Color [A=255, R=232, G=30, B=48]") { c1to3.Text = "lower"; }
        if (Convert.ToString(condor1bmp.GetPixel(553, 633)) == "Color [A=255, R=232, G=30, B=48]") { c1to4.Text = "lower"; }
        if (Convert.ToString(condor1bmp.GetPixel(553, 658)) == "Color [A=255, R=232, G=30, B=48]") { c1to5.Text = "lower"; }

        if (Convert.ToString(condor1bmp.GetPixel(553, 558)) == "Color [A=255, R=0, G=175, B=88]") { c1to1.Text = "higher"; }
        if (Convert.ToString(condor1bmp.GetPixel(553, 584)) == "Color [A=255, R=0, G=175, B=88]") { c1to2.Text = "higher"; }
        if (Convert.ToString(condor1bmp.GetPixel(553, 608)) == "Color [A=255, R=0, G=175, B=88]") { c1to3.Text = "higher"; }
        if (Convert.ToString(condor1bmp.GetPixel(553, 633)) == "Color [A=255, R=0, G=175, B=88]") { c1to4.Text = "higher"; }
        if (Convert.ToString(condor1bmp.GetPixel(553, 658)) == "Color [A=255, R=0, G=175, B=88]") { c1to5.Text = "higher"; }
        // bmp.Save("condor1.gif");
        condor1bmp.Dispose();
    }

谢谢大家,希望有人能看到我缺少的东西:(

【问题讨论】:

  • 注释掉逻辑的每个部分,直到泄漏消失。例如,注释掉wbcondor1_DocumentCompleted() 的正文——你最终还是会耗尽内存吗?
  • 根本没想过这样做。刚做了,它仍然会用完,只是在每个循环中不断构建
  • 那么这个块不是你问题的根源。在分析器中运行您的代码并查找大量分配或大量小分配,然后尝试追踪它们的来源。
  • 现在代码真的很简单,它只是一个网络浏览器和每隔 x 秒转到 x 个网站的命令:s
  • 那么浏览器历史记录可能增长过大。使用分析器,卢克。

标签: memory


【解决方案1】:

如果抛出异常,

condor1bmp.Dispose();

不会被调用。

总是使用 using 语句来包装实现 IDisposable 的东西。

除此之外,在使用位图时,除了实际内存不足之外,还有很多事情会导致 OutOfMemoryException。

有关几种可能性,请参阅

C# Out of Memory when Creating Bitmap

您的压力测试是否有可能达到这些条件之一?

【讨论】:

  • 我刚刚注释掉了文档完成部分,它仍然上升,这意味着每次我告诉网络浏览器刷新页面时,每次都会建立内存
【解决方案2】:

只是为了让人们知道谁遇到了这个错误。第 x 行内存不足。这是 Internet Explorer 本身的问题。可以通过在 IE 设置中关闭活动脚本来禁用 javascript 来停止它。

【讨论】: