Life Of A Static

Q: In my application, I am using some static fields to hold information. How do I make sure the garbage collector doesn't collect the objects referenced by the static fields? How long will the objects stay in memory?

A: A static (C#) or shared (VB) field establishes a root reference. The garbage collector will only collect objects that can't be reached directly or indirectly from a root reference. The objects you reference from static fields are safe from garbage collection.

Assuming a static field always references the same object, the object will be around for the duration of the application (for the duration of the application domain, to be precise). You'll want to be careful referencing extremely large objects with static fields, because they'll be around for a long, long time. In a web app you might consider using the ASP.NET cache instead.

The biggest concern to have with static and shared fields is thread safety. If you have multiple threads running and are modifying the objects, you'll have to make sure to do so in a thread safe way. See Statics and Thread Safety Part One and Two.

Print | posted @ Monday, July 03, 2006 1:37 AM

Comments on this entry:

Gravatar # re: Life Of A Static
by David M. Kean at 7/3/2006 2:58 PM

They are safe from Garbage Collection until the Runtime is being shut down.
  
Gravatar # re: Life Of A Static
by Milan Negovan at 7/3/2006 7:03 PM

Scott, I remember to have read this post a while ago: blogs.msdn.com/tess/archive/2006/01/23/516139.aspx Thought you'd find it interesting.
  
Gravatar # re: Life Of A Static
by scott at 7/3/2006 7:28 PM

That is a good post, Milan. Thanks!
  
Comments have been closed on this topic.