Is there any way to tell .net runtime , not to re-locate object in memory ?
IMHO – Object can be re-locate by GC when :
- Moving from one generation to another
- Being moved from
finilization-queueto thef-reachablequeue. -
else ( maybe optimization mechanism ?).
Also,I thought immutable (strings)are automatically recreated each time , so they must be created in a new location.
(just a theoratical question )
As an implementation detail, the .Net framework can move an object in the memory in the final stage of garbage collection. But this doesn’t necessarily mean moving between generations: when performing generation 2 GC, objects in gen 2 will be moved, even though they don’t change generation (because there is nowhere to go beyond gen 2).
The finalization queue and the f-reachable queue have nothing to do with this, they contain only references to objects, not the objects themselves.
I have no idea what does this have to do with immutable objects. The runtime doesn’t give any special treatment to them (except for strings).
Telling the runtime not to relocate an object (also known as “pinning” the object) is an unusual requirement and should have a really good reason, because it can negatively affect the performance of the GC. To temporarily pin an object in unsafe code, you can use the
fixedstatement. To do it permanently or from safe code, you can useGCHandle.Alloc(), specifyingGCHandleType.Pinned.