вот что советует использовать Дж. Рихтер:
System.Runtime.InteropServices.SafeHandle
Что внутри:public abstract class SafeHandle : CriticalFinalizerObject, IDisposable {
1)handle to the native resource
protected IntPtr handle;
2)конструктор
3)ВАЖНО - НЕ ПЕРЕГРУЖАТЬ:
protected virtual void Dispose(Boolean disposing) {
// The default implementation ignores the disposing argument.
// If resource already released, return
// If ownsHandle is false, return
// Set flag indicating that this resource has been released
// Call virtual ReleaseHandle method
// Call GC.SuppressFinalize(this) to prevent Finalize from being called
// If ReleaseHandle returned true, return
// If we get here, fire ReleaseHandleFailed Managed Debugging Assistant (MDA)
}
4) ВАЖНО - НЕ ПЕРЕГРУЖАТЬ:
~SafeHandle() { Dispose(false); }
5) ВАЖНО - ПЕРЕГРУЗИТЬ
protected abstract Boolean ReleaseHandle();
6) Ну и несколько полезных свойств
IsInvalid, SetHandle и тп
// These three methods have to do with security and reference counting;
// I'll talk about them at the end of this section
public void DangerousAddRef(ref Boolean success) {...}
public IntPtr DangerousGetHandle() {...}
public void DangerousRelease() {...}
}
Как использовать : наследоваться от этого класса.
Плюшки классов, наследованных от System.Runtime.ConstrainedException.CriticalFinalizerObject:
- the first time an object is constructed, the CLR immediately JIT-compiles all of the Finalizemethods in the inheritance hierarchy Under low memory conditions, the CLR might not be able to find enough memory to compile the Finalizemethod. Or the resource might not be freed if the Finalizemethod contained code that referred to a type in another assembly, and the CLR failed to locate this other assembly
- the CLR calls Finalize of CFO-derived objs after calling of Finalize of all non-CFO-derived objs. Если, например, FileStreamовый Finalize хочет сохранить что-то на диск, диск к этому моменту еще не будет закрыт (хотя мне неясно, зачем такая фича. а вдруг наоборот кто-то захочет - CFO-der. доступ к non-CFO) ????
- The CLR calls the Finalizemethod of CriticalFinalizerObject-derived types if an
App Domain is rudely aborted by a host application (such as SQL Server or ASP.NET). This also
is part of ensuring that the native resource is released even in a case in which a host application no longer trusts the managed code running inside of it