Safety of accessing freed GCHandle #46502
-
When using I expect the answer to be the same for all kinds of handles, but I am mainly using weak handles. Thanks! |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
It is not safe or reliable. Internally GCHandle is essentially an index into a table of references. When you free a handle, that entry of the table is deallocated and set to null. When you're accessing You can observe this by allocating another handle immediately after freeing one: using System;
using System.Runtime.InteropServices;
string a = "StringA";
string b = "StringB";
GCHandle handle = GCHandle.Alloc(a);
GCHandle clone = handle;
Console.WriteLine(clone.Target ?? "Null");
handle.Free();
Console.WriteLine(clone.Target ?? "Null");
GCHandle anotherHandle = GCHandle.Alloc(b);
Console.WriteLine(clone.Target ?? "Null"); Running this program will result in:
|
Beta Was this translation helpful? Give feedback.
-
If you don't have any strong requirement, using |
Beta Was this translation helpful? Give feedback.
It is not safe or reliable. Internally GCHandle is essentially an index into a table of references. When you free a handle, that entry of the table is deallocated and set to null.
When you're accessing
Target
of the dead handle, you're accessing that deallocated row of the table. If that row gets reused, it will no longer be null and will point to something else entirely.You can observe this by allocating another handle immediately after freeing one: