Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are static class members pinned?

Tags:

c#

static

I have a C# class, having a static ImageList object. This image list will be shared with various ListView headers (via SendMessage... HDM_SETIMAGELIST) on several forms in my application.

Though I understand that static objects are not eligible for garbage collection, it is not clear to me if they are also ineligible for relocation (compaction) by the garbage collector. Do I also need to pin this object since it is shared with unmanaged code, say, using GCHandle.Alloc?

Environment is VS 2008, Compact Framework 3.5.

like image 358
dablumen Avatar asked Oct 31 '22 16:10

dablumen


1 Answers

The instance itself is not static. The reference is. If you null the reference the instance becomes eligible for GC. Internally, all static instances are references through a pinned handle to an array of statics. I.e. the instance is implicitly pinned by the runtime.

If you look at the GCroot of an instance declared as a static member, you'll see something like this:

HandleTable:
    008113ec (pinned handle)
    -> 032434c8 System.Object[]
    -> 022427b0 System.Collections.Generic.List`1[[System.String, mscorlib]]

If you null the static reference the corresponding entry in the pinned array is nulled as well.

Now, these are obviously implementation details so they could potentially change.

like image 155
Brian Rasmussen Avatar answered Nov 09 '22 12:11

Brian Rasmussen