简体   繁体   English

DLL导入中的SafeFileHandle

[英]SafeFileHandle in DLL import

It's the first time I need to use P/Invoke to interact with device driver. 这是我第一次使用P / Invoke与设备驱动程序进行交互。 In DeviceIoControl function I use SafeFileHandle for handle to the device and pinvoke.net says: 在DeviceIoControl函数中,我使用SafeFileHandle来处理设备, pinvoke.net说:

If you use a SafeFileHandle, do not call CloseHandle as the CLR will close it for you. 如果您使用SafeFileHandle,请不要调用CloseHandle,因为CLR会为您关闭它。

But in C# Cookbook I found this kind signature of CloseHandle: 但在C#Cookbook中我发现了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). SafeFileHandle在其ReleaseHandle方法内部调用CloseHandle ,并且设计用于Disposable模式,因此您不希望使用CloseHandle(SafeFileHandle)手动关闭句柄(只需调用Close方法或Dispose )。

And as SafeFileHandle is sealed , I really don't see any point in the " public static extern bool CloseHandle(SafeFileHandle hObject); " signature. SafeFileHandlesealed ,我真的没有看到“ public static extern bool CloseHandle(SafeFileHandle hObject); ”签名中的任何一点。


EDIT 编辑

I just googled your book and found one CloseHandle(SafeFileHandle) reference. 我只是用Google搜索了你的书 ,发现了一个CloseHandle(SafeFileHandle)参考。 As expected, it is not used, and the SafeFileHandle is properly closed using: 正如预期的那样,它没有被使用, SafeFileHandle使用以下方法正确关闭:

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

What you see there is the Win32-API function to close an open handle . 你看到的是Win32-API函数来关闭一个打开的handle This function is to be used when you are using Win32-C/C++ and work with system-handles. 当您使用Win32-C / C ++并使用系统句柄时,将使用此函数。 I cannot validate the above statement a 100% about the CLR, but I guess you will be fine, not to use it. 我无法验证上述声明100%关于CLR,但我想你会好的,不要使用它。

See the MSDN -article on CloseHandle -function for Win32. 有关Win32的CloseHandle函数,请参阅MSDN -article。

Also there is this article here, which talks about the GC of the CLR. 这里还有这篇文章,它讨论了CLR的GC。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM