2017-02-23 47 views
1

爲什麼這個代碼產生了這麼多的內存使用,當你去在網頁瀏覽器下一個頁面(例如單擊後退和前進,3分鐘後,內存爲300 MB),任何人都可以向我解釋C#的foreach內存web瀏覽器

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

+0

爲什麼使用'+ = null'? –

+1

我覺得你正在做的是'+ ='一堆,永遠不會' - ='在這種情況下,事件堆積如山。 – MaLiN2223

+0

這是例如。空值已經增加了內存。我使用此代碼而不是null。 input.GotFocus + = GotFocusForm; input.LostFocus + = LostFocusForm; – Matthew

回答

0

無論何時訂閱事件,完成工作後,您需要取消訂閱這些事件,否則會導致內存泄漏。底線是你需要取消訂閱你訂閱的每一個事件。

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; 
     } 
    } 
}