1

Can anyone explain to me why this code generates so much memory usage when you go to next pages in webbrowser (e.g. click back and forward, after 3 minutes memory is over 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;
            }


        }

How to free memory in this case? Instead null I want to add this.

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

For a week I am looking for a solution. Thank you very much for help.

After a few back and forward. Memory

Matthew
  • 11
  • 2
  • why use `+=null`? – Lei Yang Feb 23 '17 at 01:40
  • 1
    I think what you are doing is `+=` a bunch of times and never do `-=` in that case events are piling up. – MaLiN2223 Feb 23 '17 at 01:42
  • It's for example. Null already increases memory. I am using this code instead null. input.GotFocus += GotFocusForm; input.LostFocus += LostFocusForm; – Matthew Feb 23 '17 at 01:43
  • MaLiN2223 when i used >> else input.GotFocus -= null // same problem – Matthew Feb 23 '17 at 01:44
  • @Matthew It is [well known](https://support.microsoft.com/en-us/help/893629/a-memory-leak-occurs-when-an-mshtml-instance-is-hosted-by-a-webbrowser-control-or-by-internet-explorer) that webbrowser control sometimes leaks memory. What you can do is the following: call GC.Collect() and hope for the best: simillar idea [here](http://stackoverflow.com/a/16455171/3809977) or try some profiler I think what might happend is that GC is not cleaning "right now", it will when memory resever for an application become low. You also might want to change the framework if memory is big issue here. – MaLiN2223 Feb 23 '17 at 01:54
  • MaLiN2223 you're right. After using this code, GC is not clearing. I used Gc.Collect(), changed framework from 4.5.2 to 4.6 but without changes. Is there anything else I can do? – Matthew Feb 23 '17 at 02:21

1 Answers1

0

Whenever you subscribe the event, after finishing the work you need to unsubscribe those events or it will lead to memory leak. The bottom line is you need to unsubscribe each and every event you subscribe.

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;
        }
    }
 }
AKN
  • 416
  • 2
  • 5