Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does GCHandle.Free() simply releases the handle?

Just to make sure, given that I have pinned byte array and a GCHandle on this pinned array.

When the GCHandle.Free() method is called, does it simply release the handle and hands over the management of the original byte array back to the GC, therefore if there are active references to that array, it won't be disposed just yet?

like image 386
Kel Avatar asked Mar 04 '13 16:03

Kel


2 Answers

You are right. GCHandle is just another handle to the same object, as long as you have at least one, your object won't be disposed.

However, you can allocate GCHandle with Weak type, which will allow GC to collect your object if your GCHandle is the only one pointing to it (if you have 'normal' reference as well, nothing bad will happen).

like image 67
Marcin Deptuła Avatar answered Oct 11 '22 13:10

Marcin Deptuła


Yes.

When the handle goes out of scope you must explicitly release it by calling the Free method; otherwise, memory leaks may occur. When you free a pinned handle, the associated object will be unpinned and will become eligible for garbage collection, if there are no other references to it.

-- http://msdn.microsoft.com/en-us/library/khk3k17t.aspx

like image 31
Weeble Avatar answered Oct 11 '22 12:10

Weeble