High-Performance Server Blog Post
Profiling a C# game server and improving its performance has been greatly aided by the following blog.
C# High-Performance Server - Memory Fragmentation | leafbird/devnote
In the content of the above article, it mentioned that WeakReference creates memory pinning. However, if memory is pinned, it would mean that the memory referenced by WeakReference is strongly referenced, which raises the question of whether WeakReference becomes meaningless.
`System.WeakReference` also uses pinned handles, which can lead to fragmentation.
WeakReference Does Not Pin Memory
To get straight to the point, WeakReference does not pin memory.
I searched Google and ChatGPT but could not find any information linking WeakReference to pinned handles. So, I decided to leave a dump as mentioned in the blog post to check the .NET handles.
After creating 10,000 WeakReferences and leaving a dump to check the handles, I found that instead of pinned handles, there were 10,000 Weak Short handles remaining.


For reference, types like Weak Short and Weak Long are types used internally in the .NET runtime, which is written in C++. You can find more details in runtime/src/coreclr/gc/gcinterface.h at main · dotnet/runtime · GitHub.
The accessible handle types in .NET are as follows, and WeakReference uses either the Weak or WeakTrackResurrection type depending on the creation options:
public enum GCHandleType
{
Weak,
WeakTrackResurrection,
Normal,
Pinned,
}
In any case, WeakReference does not pin memory, and therefore does not contribute to memory fragmentation.
Of course, there is a cost associated with managing the handle table in the .NET runtime and modifying the pointers of handles when the garbage collector runs, so creating too many handles may not be advisable.