Archivi tag: webbrowser control

Avoid Memory Leak in .NET

Problem: In .NET for some components like webBrowser component seems that occurs memory leaks, so we see a growth of RAM until we don’t stop our application.

Solution C#
First of all you need to declare this

[DllImport("KERNEL32.DLL", EntryPoint = "SetProcessWorkingSetSize", SetLastError = true, CallingConvention = CallingConvention.StdCall)]
internal static extern bool SetProcessWorkingSetSize(IntPtr pProcess, int dwMinimumWorkingSetSize, int dwMaximumWorkingSetSize);

[DllImport("KERNEL32.DLL", EntryPoint = "GetCurrentProcess", SetLastError = true, CallingConvention = CallingConvention.StdCall)]
internal static extern IntPtr GetCurrentProcess();

and later in your code you need to write

IntPtr pHandle = GetCurrentProcess();
SetProcessWorkingSetSize(pHandle, -1, -1);

Solution Vb.NET
First of all you need to declare this

#Region "Stuff for Closing the Processes"
'# to close all the resources
Private Declare Auto Function SetProcessWorkingSetSize Lib "kernel32.dll" (ByVal procHandle As IntPtr, ByVal min As Int32, ByVal max As Int32) As Boolean

Public Sub SetProcessWorkingSetSize()
Try
Dim Mem As Process
Mem = Process.GetCurrentProcess()
SetProcessWorkingSetSize(Mem.Handle, -1, -1)
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
#End Region

and later you need to write in your code:

GC.Collect()
If (Environment.OSVersion.Platform = PlatformID.Win32NT) Then
SetProcessWorkingSetSize(Process.GetCurrentProcess().Handle, -1, -1)
End If

Reference Link:

Microsoft Forums