I have an asynchronous socket server. I have encountered a issue where problematic clients and hard to reproduce network events cause an insane number of byte[]’s to get pinned. Since all the threading to handle clients is implicit (I use BeginAcceptClient, and I use callbacks instead of threads that are explicitly instantiated) I don’t control the pinning process. By “implicit threading” I mean threads generated not by me directly, but by the runtime hosting my application.
At any rate the answer in this post shows how to unpin objects. Is it possible to override the behind the scenes pinning if I go on ahead and pin my byte[]’s myself, do the BeginRead and unpin during cleanup?
Thanks.
The answer in the post you linked to is completely wrong (I just left a comment there). Only when the last pinning handle (more general: pinning “reason” because there are other reasons than GCHandles) is removed the object is unpinned. You cannot force unpinning. That would be terribly unsafe. You could use safe managed code to do unsafe things which is even a security problem!
Anyway, it does not make sense for you to try to prevent pinning of the object. Even if this was possible, which it is not, your process would crash at random times! Socket relies on pinning for correctness. It does not do this without reason.
The solution is elsewhere:
A small side note: Pinning is implemented differently from what you think. Pinning is not a flag you can turn on and off on an object. When you pin something, nothing special happens at first. Only when the GC runs, the GC notices that there are references with the special property that they are pinning. It then prevents the object from being moved.