OdeToCode IC Logo

Life Of A Static

Monday, July 3, 2006

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.