I am trying to embed a WebBrowser Control in a C# Winform Application. This sounds easy enough. However I discovered that the WebBrowser control eats up a lot of memory ever
I looked all over the internet and I was unable to find an answer to this problem. I fixed it using the below:
Protected Sub disposeBrowers()
If debug Then debugTrace()
If Me.InvokeRequired Then
Me.Invoke(New simple(AddressOf disposeBrowers))
Else
Dim webCliffNavigate As String = webCliff.Url.AbsoluteUri
'Dim webdollarNavigate As String = webDollar.Url.AbsoluteUri
Me.splContainerMain.SuspendLayout()
Me.splCliffDwellers.Panel2.Controls.Remove(webCliff)
Me.splDollars.Panel2.Controls.Remove(webDollar)
RemoveHandler webCliff.DocumentCompleted, AddressOf webCliff_DocumentCompleted
RemoveHandler webDollar.DocumentCompleted, AddressOf webDollar_DocumentCompleted
RemoveHandler webCliff.GotFocus, AddressOf setDisposeEvent
RemoveHandler webCliff.LostFocus, AddressOf setDisposeEvent
RemoveHandler webDollar.GotFocus, AddressOf setDisposeEvent
RemoveHandler webDollar.LostFocus, AddressOf setDisposeEvent
webCliff.Stop()
webDollar.Stop()
Dim tmpWeb As SHDocVw.WebBrowser = webCliff.ActiveXInstance
System.Runtime.InteropServices.Marshal.ReleaseComObject(tmpWeb)
webCliff.Dispose()
tmpWeb = webDollar.ActiveXInstance
System.Runtime.InteropServices.Marshal.ReleaseComObject(tmpWeb)
webDollar.Dispose()
webCliff = Nothing
webDollar = Nothing
GC.AddMemoryPressure(50000)
GC.Collect()
GC.WaitForPendingFinalizers()
GC.Collect()
GC.WaitForFullGCComplete()
GC.Collect()
GC.RemoveMemoryPressure(50000)
webCliff = New WebBrowser()
webDollar = New WebBrowser()
webCliff.CausesValidation = False
webCliff.Dock = DockStyle.Fill
webDollar.CausesValidation = webCliff.CausesValidation
webDollar.Dock = webCliff.Dock
webDollar.ScriptErrorsSuppressed = True
webDollar.Visible = True
webCliff.Visible = True
Me.splCliffDwellers.Panel2.Controls.Add(webCliff)
Me.splDollars.Panel2.Controls.Add(webDollar)
Me.splContainerMain.ResumeLayout()
'vb.net for some reason automatically recreates these and the below is not needed
'AddHandler webCliff.DocumentCompleted, AddressOf webCliff_DocumentCompleted
'AddHandler webDollar.DocumentCompleted, AddressOf webDollar_DocumentCompleted
'AddHandler webCliff.GotFocus, AddressOf setDisposeEvent
'AddHandler webCliff.LostFocus, AddressOf setDisposeEvent
'AddHandler webDollar.GotFocus, AddressOf setDisposeEvent
'AddHandler webDollar.LostFocus, AddressOf setDisposeEvent
webCliff.Navigate(webCliffNavigate)
'webDollar.Navigate(webdollarNavigate)
disposeOfBrowsers = Now.AddMinutes(20)
End If
End Sub
I know this is not the prettiest or perfect solution, but it worked very well for me. -- Layla