Reputation: 2994
When we analyse memory heaps, following 4 types of GC handles we generally come across:
Weak:- A weak GC handle will not prevent the instance it corresponds to from being garbage collected. Example, used by the System.WeakReference class instances
.
Normal:- A normal GC handle prevents the corresponding instance from being garbage collected.Example, used by the instances of strong references
.
RefCounted:- A reference counted GC handle is used internally by the runtime, example, when dealing with COM interfaces.
Pinned:- Why do we need this kind of GC handle? Is it just for avoiding the movement of that instance in memory or is there any other notion behind this? I want to know the notion behind Pinned GC handle(with an example).
Edited for Itay's answer:- I have a non empty array-DiffCell[][] which is bound to a data grid in WPF. When I close the window on which this data grid is present, on heap I see Pinned GC handle pointing to this empty DiffCell array through object[](see snapshot). I am not using any unsafe code. I am just setting ItemsSource of data grid to null before closing that window. So my question is who does pin this array on heap and why?
Upvotes: 14
Views: 4693
Reputation: 19781
Dont forget GCHandle which supports pinning objects (and retrieving the address as an IntPtr). Pinning objects aren't exclusive to unsafe code (the fixed statement).
Upvotes: 3
Reputation: 18296
We need this in case we use pointers.
Imagine that you declare a pointer to a memory location and you do not pin in.
The GC sometimes move memory chunks to other places so your pointer will get invalid.
for example:
public unsafe void DoSomething(byte b)
{
byte * bp = &b;
}
this will not compile because you didn't fix memory location that holds the byte.
In order to pin it you can use:
public unsafe void DoSomething(byte b)
{
fixed(byte * bp = &b)
{
//do something
}
}
Upvotes: 7