C # window handle /. NET

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

Are there any significant pros / cons?

Thank.

+1


source to share


2 answers


I wouldn't think it SafeHandle

would add any value. MSDN provides the following usage notes SafeHandle

(emphasis mine):

The SafeHandle class provides protection against handle-protected attacks; it also ensures the critical completeness of the descriptor resources. This class allows you to pass to unmanaged code a handle to an unmanaged resource (for example, an operating system handle) wrapped in an instance of a derived class. It provides protection against security attacks through processing . An example of disposing of handles is an untrusted user of your handle trying to enqueue operations against a resource on one thread while closing the handle on another. An untrusted user will do this in the hope that the handle will be reused by some unrelated thread in the process, and the in-process operation returns or modifies data that would normally not be available to the caller.SafeHandle also provides critical termination : the ReleaseHandle method is triggered even if the AppDomain is unloaded by the host, or if normal finalizers block or take too long to clean up.

Neither of these two targets apply to a window handle returned from a Windows Forms object Control

. The handle handling seems controversial given the typical usage conditions of the property Control

Handle

, and the structure and operating system take any finalization issues out of your hands with window handles.



Another way to think about is to use SafeHandle

, you need to provide an implementation for the property IsInvalid

and method ReleaseHandle

. The property Control.Handle

never returns an invalid value to my knowledge, and the window handle will and should be "freed" when the control is removed.

However, the framework itself wraps the window handles in an object HandleRef

when it uses them, which simply protects the control from the garbage collector while the handle is used by unmanaged code. This is something that you are unlikely to need in typical scenarios for which you need a window handle, but there is almost no work to use it if there is such a possibility that you might need it.

+1


source


It depends on it:)

If a handle is returned in such a way that you must end up calling version :: CloseHandle on them, you must always subclass SafeHandle. SafeHandle makes the strongest guarantee possible in the .NET Framework that the handle will be released. Failure to free the IntPtr will result in a resource leak. Enough resource leaks will eventually cause the program to crash.



If the descriptor does not need to be freed, then it is sufficient to bypass IntPtr.

+2


source







All Articles