tags:

views:

2385

answers:

2

When working with window handles, is it good enough to use the plain IntPtr or should I subclass SafeHandle?

Are there any significant pros/cons?

Thanks.

+2  A: 

That depends :)

If the handle is returned in such a way that you must eventually call a version of ::CloseHandle on them then you should always subclass SafeHandle. SafeHandle makes the strongest guarantee possible in the .Net Framework that a handle will be freed. Not freeing an IntPtr will lead to a resource leak. Enough resource leaks will eventually lead to a program crash.

If the handle doesn't need to be freed then passing around IntPtr is sufficient.

JaredPar
+1  A: 

I wouldn't think that SafeHandle would add any value. MSDN provides the following remarks on the usage of SafeHandles (emphasis mine):

The SafeHandle class provides protection for handle recycling security attacks; it also provides critical finalization of handle resources. This class allows you to pass to unmanaged code a handle to an unmanaged resource (such as an operating system handle) wrapped in a derived class instance. It provides protection against security attacks by recycling handles. An example of handle recycling is an untrusted user of your handle attempting to queue operations against the resource on one thread while closing the handle on another. The untrusted user would do this in the hope that the handle is reused immediately by some unrelated thread in the process, and the in-process operation returns or alters data that is normally inaccessible to the caller. SafeHandle also provides critical finalization: the ReleaseHandle method is run even when the AppDomain is unloaded by the host, or if normal finalizers block or take too long to clean up.

Neither of these two goals seems applicable to a window handle returned from a Windows Forms Control object. Handle recycling seems moot given typical usages of a Control's Handle property, and the framework and the operating system take any finalization issues out of your hands with window handles.

Another way to think of it is this: to use SafeHandle, you'd have to provide an implementation for the IsInvalid property and the ReleaseHandle method. The Control.Handle property will never, to my knowledge, return an invalid value, and the window handle will be and should only be "released" when the control is disposed.

That said, the framework itself does wrap window handles in a HandleRef object when it uses them, which simply protects the control from the garbage collector while the handle is being used by unmanaged code. This is something you're unlikely to need in the typical scenarios you'd need a window handle, but it takes almost no work to use it, if there's a possibility you might need it.

P Daddy