Sandeep
Sandeep

Reputation: 61

memory not released WPF

I have developed a sample WPF application that has one window with one button When application is opened, if observed from task manager, memory occupied: 12.3 MB

Dim b As Boolean = False
Private lst As List(Of String)
Private Sub Btn_Close(sender As Object, e As RoutedEventArgs)
    If b = False Then
        If lst Is Nothing Then lst = New List(Of String)
        For i As Integer = 0 To 30
            lst.Add(Convert.ToBase64String(IO.File.ReadAllBytes("d:\test.txt"))) 'memory increases, test.txt file is a 2MB file
        Next
        'do some operations with lst object
        'memory occupied: 133MB
        'now again click the same button, it will go to else case now (cause of the last statement)
    Else
        lst.Clear()
        If MsgBox("GC.Collect()?", MsgBoxStyle.YesNo) = MsgBoxResult.Yes Then
            GC.Collect()
            'in this case, memory occupied: 13MB
        Else
            'in this case, memory occupied: 133MB, not cleared
        End If
    End If
    b = Not b
End Sub

Only when GC.Collect() statement is executed memory is released, otherwise the memory stays at 133MB only.

I have requirement in a way when click on any button, a new window opens as showdialog that contains a grid with thousands of records, say: 6000 to 1Lakh, here I do some operations with the selected records (here memory increases) and then closes the window. After closing the window, the memory is not released, I explicitly have to execute the statement GC.Collect()

Is there any thing wrong in the code? or why do I need to explicitly call GC.Collect as CLR will take care of it automatically? (in my application, if I repeat above and don't use GC.Collect, I get outofmemory exception after some time)

Upvotes: 0

Views: 362

Answers (1)

Dan Puzey
Dan Puzey

Reputation: 34198

There's nothing wrong with your code, and there's nothing wrong with your memory consumption either. There is no guarantee that closing your form will immediately release the memory; indeed, GC will reclaim the memory when it needs to, which is very often not when a developer expects it to.

Garbage collection in .NET fires automatically in response to allocations of memory - that is, when you try to declare an object that doesn't fit in the heap's current Gen0, a garbage collection will occur.

The real question to ask here is: why do you have an issue with the memory staying at 133MB? Is it causing you a problem? Unless you have a specific requirement for this memory to be collected, I'd say don't GC.Collect(), and let the framework work it out for you.

(It's worth noting that calling GC.Collect() manually often has a negative effect on the long-term memory consumption of an application.)

Upvotes: 2

Related Questions