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.

David M. Kean Monday, July 3, 2006
They are safe from Garbage Collection until the Runtime is being shut down.
Milan Negovan Monday, July 3, 2006
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.
scott Monday, July 3, 2006
That is a good post, Milan. Thanks!
Comments are closed.