Are SafeHandle and derived types always safe? #1473
harborsiem
started this conversation in
General
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
I found an interesting expression in the book from Jeffrey Richter (CLR via CSharp, 4th edition, page 528).
See following code and text from the book:
You’ll notice that the CreateEventBad method is prototyped as returning an IntPtr, which will
return the handle back to managed code; however, interoperating with native code this way is not
robust. You see, after CreateEventBad is called (which creates the native event resource), it is possible
that a ThreadAbortException could be thrown prior to the handle being assigned to the handle
variable. In the rare cases when this would happen, the managed code would leak the native resource.
The only way to get the event closed is to terminate the whole process.
The SafeHandle class fixes this potential resource leak. Notice that the CreateEventGood method
is prototyped as returning a SafeWaitHandle (instead of an IntPtr). When CreateEventGood is
called, the CLR calls the Win32 CreateEvent function. As the CreateEvent function returns to
managed code, the CLR knows that SafeWaitHandle is derived from SafeHandle, causing the CLR to
automatically construct an instance of the SafeWaitHandle class on the managed heap, passing in
the handle value returned from CreateEvent. The constructing of the SafeWaitHandle object and
the assignment of the handle happen in native code now, which cannot be interrupted by a
ThreadAbortException. Now, it is impossible for managed code to leak this native resource.
Eventually, the SafeWaitHandle object will be garbage collected and its Finalize method will be
called, ensuring that the resource is released.
My comment:
When I take a look to the construction what CsWin32 does, it looks more like a CreateEventBad (see code below).
So the user of these functions have to pay attention in multi threaded applications to have no leak in the native resource if there is a ThreadAbortException. (Calling the function with lock statement ?)
What can CsWin32 do better ? Can the fixed statement do the job that an other thread is blocked at this time ?
Beta Was this translation helpful? Give feedback.
All reactions