开发者

How can I reduce memory in VB.NET Windows application?

I am working on VB.NET multiuser application and whenever any of my forms opens up - memory rises, and after some time OutOfMemoryException is thrown.

I am working on VB.net 2008 and SqlServer 2005. I have used very many of shared object so second time its memory allocation is less, but how i can reduce it when form is closed or开发者_开发问答 not in use. Can i use Garbage collector or Dispose and how I use this functionality ?


Are you detaching all event handlers as needed? This is a common source of memory leaks in .NET applications.

You can troubleshoot this by using tools like ANTS Memory Profiler or if you prefer a free option WinDbg+SOS is very useful (but not as easy to use).


using .net Garbage collection is an automatic process, getting rid of any unused objects in memory.

A lot of memory can be "lost" to the program while waiting for garbage collection.

Normally you should leave the Garbage Collector alone. It usually does a decent job of deciding when cleaning house will be worthwhile.

But you may wish to force its hand every now and then.

There is a very simple call to clear the garbage collection.

GC.Collect()

Hope this helps.

Although, you probably have some other issues to be getting out of memory exception.

Are you dealing with imagery by chance?


Try this code for RAM MEMORY released :

First declare this function :

Private Declare Function SetProcessWorkingSetSize Lib "kernel32.dll" (ByVal hProcess As IntPtr, ByVal dwMinimumWorkingSetSize As Int32, ByVal dwMaximumWorkingSetSize As Int32) As Int32

And this is the usage of it :

Friend Sub ReleaseMemory()
    Try
        GC.Collect()
        GC.WaitForPendingFinalizers()
        If Environment.OSVersion.Platform = PlatformID.Win32NT Then
            SetProcessWorkingSetSize(System.Diagnostics.Process.GetCurrentProcess().Handle, -1, -1)
        End If
    Catch ex As Exception
        LogError(ex.ToString())
    End Try
End Sub


Make sure you remove all reference to an object when you don't need it anymore. (or all reference to the parent object)

If one of your active forms still uses an object you don't need, the garbage collector will assume you still need it and won't remove it from memory.

Don't forget to call .Dispose() when needed.

There's some great tool out there that can give you a hint on where your memory problem is.


The best :

Public Class FreeMemory Private Declare Function SetProcessWorkingSetSize Lib "kernel32.dll" ( _ ByVal process As IntPtr, _ ByVal minimumWorkingSetSize As Integer, _ ByVal maximumWorkingSetSize As Integer) As Integer

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

End Class

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜