A Blog Post on High-Performance C# Servers
The following blog post was very helpful when I was profiling and improving the performance of a C# game server.
High-Performance C# Servers - Memory Fragmentation | leafbird/devnote
The post said that WeakReference causes memory pinning.
I wondered whether pinning the memory would create a strong reference to the memory pointed to by WeakReference,
making the WeakReference pointless.
`System.WeakReference`도 pinning handle을 사용하고 있어, 단편화 유발의 원인이 된다.
WeakReference Does Not Pin Memory
To get straight to the point, WeakReference does not pin memory.
I searched Google and asked ChatGPT, but I couldn't find anything connecting WeakReference to pinned handles.
So, following the approach mentioned in the blog post, I captured a dump and checked the .NET handles myself.
After creating 10,000 WeakReference instances, I captured a dump and inspected the handles.
I found 10,000 Weak Short handles, not pinned handles.


For reference, types such as Weak Short and Weak Long are used internally by the .NET runtime, which is written in C++.
runtime/src/coreclr/gc/gcinterface.h at main · dotnet/runtime · GitHub
There are four handle types accessible from .NET, as shown below. WeakReference uses either Weak or WeakTrackResurrection, depending on how it is created.
public enum GCHandleType
{
Weak,
WeakTrackResurrection,
Normal,
Pinned,
}
In any case, WeakReference does not pin memory and therefore does not contribute to memory fragmentation.
That said, the .NET runtime incurs costs for managing the handle table and updating handle pointers during garbage collection,
so creating too many handles is probably not a good idea.