views:

142

answers:

3

If I have an object stored in memory, and I walk away from my application for an hour, will the object still be there when I get back?

In other words, will the .NET garbage collector throw my object away because it hasn't been used for awhile?

+11  A: 

The garbage collector only collects objects that are no longer referenced in your application. The garbage collector will never collect any objects that are being used.

The garbage collector's definition of "being used" is based on roots. An object instance has roots if other object instances in the AppDomain reference it. As long as the AppDomain that hosts your application is not unloaded, any and all object instances that were in memory will remain in memory as long as they retain roots in the application.

Andrew Hare
+4  A: 

As long as there is something referencing your object, it will not be collected by the garbage collector. So, if you create a static field in a class and assign it with a reference to your object, it will remain in memory as long as there is not another assignment to the field, and as long as the AppDomain is loaded (which typically is as long as the process is running).

Fredrik Mörk
+3  A: 

+1 for @Andrew's answer - yet - your app memory can be gone into the virtual memory (on the DISK) so when you access the object, it will take a little time to get it, yet it will be there eventually.

Dani