NvrBst said:
Just for clarification, the Microsoft.Win32.SafeHandles.SafeFileHandle
can be used with anything that uses the "kernel32's CloseHandle"
method for clean up?
From this I gather that you plan on being lazy instead of deriving a new
class from SafeHandle. Please don't be lazy. It makes your code harder to
read and allows typing mistakes. It's really not hard:
internal static class SafeNativeMethods {
[DllImport("kernel32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool CloseHandle(IntPtr handle);
}
sealed class SafeProcessHandle : SafeHandle {
public SafeProcessHandle () : base(IntPtr.Zero, true) { }
public SafeProcessHandle (IntPtr handle, bool ownsHandle) :
base(IntPtr.Zero, ownsHandle) {
base.handle = handle;
}
public override bool IsInvalid {
get { return base.handle == IntPtr.Zero; }
}
protected override bool ReleaseHandle() {
return SafeNativeMethods.CloseHandle(base.handle);
}
}
Note that you usually inherit from SafeHandleZeroOrMinusOneIsInvalid, but I
like being pedantic here as -1 is a valid process handle (to the current
process).
Yes, you *can* store anything that's closed with CloseHandle() in a
SafeFileHandle and it'll work (just as a HANDLE is a HANDLE), but having
explicitly typed handles is a lot nicer.