0

I have a timer running every 1/10 second (Interval = 100). It is in an infinte loop because I want to load a site on my WebBrowser control and get info into a span ID each time it loads. My problem is if this process runs for a long time, it'll be a memory leak.

In 30 minutes, memory usage can be 800MB or more. How do I prevent my program from continuously using more memory as it runs?

Here is the relevent code. It does not include any of the process creation code yet.

private void buttonBid_Click(object sender, EventArgs e)
{
    ID = Convert.ToInt32(textBoxID.Text);
    getItem();
    return;
}

private void getItem()
{
    webBrowser.Url = new Uri("http://www.test.com/?id=" + ID);
    webBrowser.DocumentCompleted += webBrowser_DocumentCompleted;
    return;
}

private void webBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
    timerLoad.Start();
    return;
}

private void timerLoad_Tick(object sender, EventArgs e)
{
    var elem = webBrowser.Document.GetElementById("product_" + ID);

    textBoxProduct.Text = Convert.ToString(elem.InnerText);

    timerLoad.Dispose();
    timerLoad.Start();
}
Paolo Moretti
  • 54,162
  • 23
  • 101
  • 92
Mekhy
  • 21
  • 3

2 Answers2

4

A possible source for memoryleaks is multiple event bindings.

You bind the DocumentCompleted event each time the GetItem method is invoked. You should bind the DocumentCompleted once, for instance in the constructor of your class.

However if you pressed the button just once, this will not be your main problem.

I would like to recommend .NET Memory Profiler 4.0 to troubleshoot your problem.

Also, I have searched a little bit further and your problem might be in the use of the WebBrowser component: See this question.

Community
  • 1
  • 1
Myrtle
  • 5,761
  • 33
  • 47
0

This is something you should do only once at creation time or so

    webBrowser.DocumentCompleted += webBrowser_DocumentCompleted;

These can be removed. At least I think they serve no purpose and might be problematic

    timerLoad.Dispose();
    timerLoad.Start();

If I read your code correct the timerLoad.Start(); should be a Stop(); as the Tick loads the document and should then stop working until the next buttonclick, right?

IvoTops
  • 3,463
  • 17
  • 18
  • click button once time and program will running until can't read data from site, program will be stop. – Mekhy Jul 20 '12 at 15:58