Sunday, September 11, 2005

PDC Precon: SafeHandle



One last thought from Jeff Richter's talk on the .Net Framework 2.0 today. SafeHandles. The idea is that you should wrap all unmanaged resources with SafeHandles instead of IntPtr and update your pinvoke signatures to use them as well.

They provide safety in scenarios where you need to keep your object alive when it could be called by by unmanaged code, ensures that reference assignments occur so that you don't incur a memory/resource leak and prevents handle recycle attacks. Here is a SafeHandle Case Study.

Anyhow, the interesting thing he mentioned was that deriving your own SafeHandle classes to wrap unmanaged resources replaces implementing IDisposable and finalizers. Happy, happy, joy, joy! The SafeHandle internally implements IDisposable and the finalizer following the correct pattern.

That said, you still have to call Dispose() on any SafeHandles to ensure they are collected in a deterministic fashion. That ensures optimal performance since the Garbage Collector algorithms are based only on the managed heap.

As with 1.0 and 1.1, you can track the finalizer thread with a profiler to ensure that Dispose() is being called (since that will suppress the finalize) since the SafeHandle base class still implements that pattern.

I also heard that with 2.0 there will be additional profiler APIs that will enable object tracking so that it will be easier to see where an object that is being finalized was created.

I'm so glad that we no longer have to implement that horrible IDisposable pattern anymore.

0 Comments:

Post a Comment

<< Home