Question Thread And Memory Usage

anthony.selby

Well-known member
Joined
Sep 3, 2009
Messages
65
Programming Experience
5-10
So I'm looking at the following code:

VB.NET:
   Sub Main()
        Dim MinMem As Integer = 999999999
        Dim MaxMem As Integer = -99999
        Dim MinMemCount As Integer
        Dim MaxMemCount As Integer
        Dim Total As Long
        Dim Average As Integer = 0

        For count = 1 To 1000
            Dim c As Process = Process.GetCurrentProcess
            Dim TempThread As New Threading.Thread(AddressOf Counter)
            TempThread.Start()
            Threading.Thread.Sleep(250)
            If count > 10 Then
                If MinMem > c.WorkingSet64 / 1024 Then
                    MinMem = c.WorkingSet64 / 1024
                    MinMemCount = count
                End If
            End If
            If MaxMem < c.WorkingSet64 / 1024 Then
                MaxMem = c.WorkingSet64 / 1024
                MaxMemCount = count
            End If
            Total = Total + (c.WorkingSet64 / 1024)
            If count / 10 = Int(count / 10) Then
                Average = Int(Total / count)
            End If
            Console.WriteLine("Runs: " & count & " Usage: " & c.WorkingSet64 / 1024 & " MinMem: " & MinMem & " (" & MinMemCount & ") MaxMem: " & MaxMem & " (" & MaxMemCount & ") Average: " & Average)
        Next

    End Sub

    Private Sub Counter()
        Dim Count As Integer
        For Count = 0 To 1000

        Next

    End Sub

Whenever this runs, and if i increase the number of times it runs I never get back to the amount of memory used in the first ten iteration ? Am I missing something shouldn't the garbage collector kick in and release that memory back. After 1000 iterations the min memory useage still happened somewhere under 10 iterations and the max memory useage happens at a higher and higher number ?

Something isn't being let go ? any ideas what I'm doing wrong ?
 
Try minimising the app and restoring it. Does the memory usage drop? If so then you've got nothing to worry about. If not, that's and indication that your code is retaining references to objects that you no longer need.
 
Try minimising the app and restoring it. Does the memory usage drop? If so then you've got nothing to worry about. If not, that's and indication that your code is retaining references to objects that you no longer need.
If you for example use Vista the Task Manager shows only Private Workset by default (and no changes by minimizing), previous versions displayed Workset. If you show Workset column also this is less affected in Vista by minimizing the app. I don't know if this is caused by a higher usage of shared .Net resources or other changes, but you won't see the 1mb-ish numbers that were typical before.
 
Back
Top