我正在开发一个.NET库,以便通过.NET代码方便地使用LibTiePie。
相关图书馆代码(C#):
using Handle = UInt32;
public static class API
{
[DllImport(@"libtiepie.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern void DevClose(Handle device);
};
public class Device
{
protected Handle _handle;
public Device(Handle handle)
{
_handle = handle;
}
~Device()
{
API.DevClose(_handle);
}
}程序代码(C#):
Device dev = new Device( some_valid_open_handle );
// Do something useful with dev
dev = null; // How can I make sure that the handle is closed now, as the GC may not cleanup it directly?我可以添加Close方法,Device类,它可以在释放引用之前调用。但奇怪的是,是否有更好的.NET方式来实现这一点呢?
发布于 2014-01-30 12:28:20
实现IDisposable接口。
然后,消费者可以:
using (Device d = new Device(handle))
{
...
} 这将提供基础句柄的确定性关闭。还请参阅关于使用关键字的文档。
而不是在终结器中调用API.DevClose(_handle),然后在Dispose()中这样做。MSDN链接有一个很好的例子,说明如何使用此模式关闭本机句柄。
https://stackoverflow.com/questions/21456482
复制相似问题