SafeFileHandle when importing a DLL

This is the first time I need to use P / Invoke to interact with a device driver. In the DeviceIoControl function, I use SafeFileHandle to control the device and pinvoke.net says:

If you use SafeFileHandle, do not call CloseHandle, as the CLR will close it for you.

But in the C # cookbook, I found this signature of type CloseHandle:

[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool CloseHandle(SafeFileHandle hObject);

What is the truth?

+5
source share
2 answers

SafeFileHandleinternally calls CloseHandlein its method ReleaseHandleand is intended for use with a template Disposable, so you do not want to manually close the handle with CloseHandle(SafeFileHandle)(just call the Closeor method Dispose).

SafeFileHandle - sealed, <<29 > .


CloseHandle(SafeFileHandle). , , SafeFileHandle , :

private void ClosePipe() 
{ 
    if (!_handle.IsInvalid) 
    { 
        _handle.Close(); 
    } 
}
+5

, Win32-API handle. , Win32-C/++ . 100% CLR, , , .

. MSDN - CloseHandle - Win32.

, GC CLR.

+1

All Articles