【问题标题】:c# Foreach memory webbrowserc# Foreach 内存浏览器
【发布时间】:2017-07-13 07:54:23
【问题描述】:

谁能向我解释为什么当您在浏览器中转到下一页时这段代码会产生如此多的内存使用(例如,单击后退和前进,3 分钟后内存超过 300 MB)

private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
    {
        foreach (HtmlElement input in webBrowser1.Document.GetElementsByTagName("input"))

        {

            if (input.GetAttribute("type").ToLower() == "text")
            {
                input.GotFocus += null;
                input.LostFocus += null;
            }


        }

在这种情况下如何释放内存?相反,我想添加这个。

void GotFocusForm(object sender, EventArgs e)
    {
        Form2.Instance.Show();
    }
    void LostFocusForm(object sender, EventArgs e)
    {
        Form2.Instance.Hide();
    }

一周以来,我一直在寻找解决方案。非常感谢您的帮助。

经过几次来回。 Memory

【问题讨论】:

  • 为什么要使用+=null
  • 我认为你正在做的是+= 很多次,永远不要做-= 在这种情况下事件正在堆积。
  • 例如。 Null 已经增加了内存。我正在使用此代码而不是 null。输入.GotFocus += GotFocusForm; input.LostFocus += LostFocusForm;
  • MaLiN2223 当我使用 >> else input.GotFocus -= null // 同样的问题
  • @Matthew 是well known webbrowser 控件有时会泄漏内存。你可以做的是:调用 GC.Collect() 并希望最好:类似的想法here 或尝试一些分析器我认为可能发生的是 GC 没有“现在”清理,它会在内存恢复时清理申请变低。如果这里的内存是大问题,您可能还想更改框架。

标签: c# memory foreach


【解决方案1】:

无论何时订阅事件,完成工作后都需要取消订阅这些事件,否则会导致内存泄漏。底线是您需要取消订阅您订阅的每个事件。

private void webBrowser1_DocumentEventCleanup()
{
    foreach (HtmlElement input in webBrowser1.Document.GetElementsByTagName("input"))
    {
        if (input.GetAttribute("type").ToLower() == "text")
        {   //unsubscribe all the subscribe events
            input.GotFocus -= null;
            input.LostFocus -= null;
        }
    }
 }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-15
    • 2011-03-08
    • 2011-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多