J
John Kiernander
I've just come across an interesting problem (?) in VB.NET. It seems
that a for..each loop prevents the garbage collector from being able
to clean up an object. Check out the two code sections below (if you
want to replicate this problem I suggest you use a pretty big data
table so that the memory footprint will be visible through task
manager):
Example 1:
For Each dtrThis In dtbThis.Rows
Next
dtrThis = Nothing
dtbThis.Dispose()
dtbThis = Nothing
GC.WaitForPendingFinalizers()
GC.Collect()
Example 2:
For intThis = 0 to dtbThis.Rows.Count - 1
Next
dtbThis.Dispose()
dtbThis = Nothing
GC.WaitForPendingFinalizers()
GC.Collect()
I (perhaps incorrectly) assumed that these two cases would behave in
the same way. However upon collection, example 2 frees a large
datatable sized chunk of memory, whereas in example 1 the collection
doesn't seem to free anything.
There is obviously a logical explanation for this behaviour, but it
escapes me.
Any thoughts?
John
that a for..each loop prevents the garbage collector from being able
to clean up an object. Check out the two code sections below (if you
want to replicate this problem I suggest you use a pretty big data
table so that the memory footprint will be visible through task
manager):
Example 1:
For Each dtrThis In dtbThis.Rows
Next
dtrThis = Nothing
dtbThis.Dispose()
dtbThis = Nothing
GC.WaitForPendingFinalizers()
GC.Collect()
Example 2:
For intThis = 0 to dtbThis.Rows.Count - 1
Next
dtbThis.Dispose()
dtbThis = Nothing
GC.WaitForPendingFinalizers()
GC.Collect()
I (perhaps incorrectly) assumed that these two cases would behave in
the same way. However upon collection, example 2 frees a large
datatable sized chunk of memory, whereas in example 1 the collection
doesn't seem to free anything.
There is obviously a logical explanation for this behaviour, but it
escapes me.
Any thoughts?
John