It's the first time I need to use P/Invoke to interact with device driver. In DeviceIoControl function I use SafeFileHandle for handle to the device and pinvoke.net says:
If you use a SafeFileHandle, do not call CloseHandle as the CLR will close it for you.
But in C# Cookbook I found this kind signature of CloseHandle:
[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool CloseHandle(SafeFileHandle hObject);
What's the truth?
SafeFileHandle
internally calls CloseHandle
in its ReleaseHandle
method, and is designed to be used in with a Disposable
pattern, so you don't want to manually close the handle with CloseHandle(SafeFileHandle)
(just call the Close
method, or Dispose
, instead).
And as SafeFileHandle
is sealed
, I really don't see any point in the " public static extern bool CloseHandle(SafeFileHandle hObject);
" signature.
EDIT
I just googled your book and found one CloseHandle(SafeFileHandle)
reference. As expected, it is not used, and the SafeFileHandle
is properly closed using:
private void ClosePipe()
{
if (!_handle.IsInvalid)
{
_handle.Close();
}
}
What you see there is the Win32-API function to close an open handle
. This function is to be used when you are using Win32-C/C++ and work with system-handles. I cannot validate the above statement a 100% about the CLR, but I guess you will be fine, not to use it.
See the MSDN -article on CloseHandle
-function for Win32.
Also there is this article here, which talks about the GC of the CLR.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.