Without pointing me to MSDN, could someone give a concise, clear explanation of the purpose of each of these and when to use them. (IntPtr, SafeHandle and HandleRef)
HWnd a = new HWnd();
B.SendMessage(a.Handle, ...);
Assuming this is the only reference to "a" in the program, this is equivalent to:
HWnd a = new HWnd();
IntPtr h = a.Handle;
// a is no longer needed and thus can be GC'ed
B.SendMessage(h, ...);
The problem is that when "a" is disposed, it will close the handle. If this happens before or during the call to SendMessage, the handle will be invalid.
HandleRef prevents "a" from being garbage collected before the program is done with h.
It looks like SafeHandle does incorporate HandleRef's KeepAlive behavior: Project Roslyn SafeHandle.cs http://referencesource.microsoft.com/#mscorlib/system/runtime/interopservices/safehandle.cs,743afbddafaea263
/*
Problems addressed by the SafeHandle class:
1) Critical finalization - ensure we never leak OS resources in SQL. Done
without running truly arbitrary & unbounded amounts of managed code.
2) Reduced graph promotion - during finalization, keep object graph small
3) GC.KeepAlive behavior - P/Invoke vs. finalizer thread ---- (HandleRef)
<...>
*/
But I'm not sure, it looks like keepalive behavior can only be acheived by providing false value to the constructor which simply marks object as not finalizable, so you have to call SafeHandle's Dispose() manualy to prevent resource leakage in that case, am I right? Can someone explain source code, what is the
private extern void InternalDispose();
private extern void InternalFinalize();
?
IntPtr
is just a simple integer-based struct that can hold a pointer (ie., 32 bit size on 32-bit systems, 64-bit size on 64-bit systems).
SafeHandle
is a class that is intended to hold Win32 object handles - it has a finalizer that makes sure that the handle is closed when the object is GC'ed. SafeHandle
is an abstract class because different Win32 handles have different ways they need to be closed. Prior to the introduction of SafeHandle
, IntPtr
was used to hold Win32 handles, but ensuring that they were properly closed and prevented from being GC'ed was the responsibility of the programmer.
HandleRef
is a way to make sure that an unmanaged handle is not GC'ed when you're in the middle of a P/Invoke call. Without something like HandleRef
, if your managed code doesn't do anything with the handle after the P/Invoke call, if the GC were run during the P/Invoke call it would not realize that the handle was still in use and might GC it. I imagine (but I'm not sure and haven't looked) that SafeHandle
might use HandleRef
as part of its management of the encapsulated handle.