Re:Allocation is cheap in .NET until it is not
by johncolanduoni on Wednesday January 24, 2018 @06:17PM
(#16227260)
> (I believe once the GCHandle is freed/finalized by the GC, it will automatically unpin the object.)
GCHandle is a struct so you have to explicitly call GCHandle.Free().
Typically this isn't a big problem - pinned data structures in .NET code are either pinned for short periods of time (to pass to native code), or are reusable large big buffers that stay pinned forever. Large buffers are always allocated in the large object heap right away. You can always allocate native memory directly in which case the GC doesn't care about it.
This may be changing since recent updates to C# and the runtime have introduced the concept of interior pointers to objects, where you can have a raw pointer to a field within a GCable object. Right now those are constrained to living on the stack only, so the period of time in which the object can't be moved/compacted as a result is relatively short.