Question

I have unmanaged code that calls an asynchronous managed method that returns a handle, and then the unmanaged code uses that handle to wait. According to the documentation, SafeWaitHandle provides 2 other methods (DangerousAddRef and DangerousRelease ). Should I use these methods in order to prevent the Handle from not being released? As the name of the method DangerousGetHandle suggest, it seems to me that I should be very careful with something, what is so dangerous here?

Edit: Is there a better way to implement this scenario (not dangerously)?

Was it helpful?

Solution

If the managed method returns the handle, but doesn't pass ownership of the handle to the calling unmanaged method, then you should just return the handle as a SafeWaitHandle directly (it will be marshalled to a handle) - this way unmanaged code doesn't have to worry about releasing the handle.
If you want to pass ownership of the handle to the unmanaged method, then you should call DangerousAddRef before returning the handle, but then you have to release the handle using unmanaged code.

OTHER TIPS

From MSDN:

Using the DangerousGetHandle method can pose security risks because, if the handle has been marked as invalid with SetHandleAsInvalid, DangerousGetHandle still returns the original, potentially stale handle value. The returned handle can also be recycled at any point. At best, this means the handle might suddenly stop working. At worst, if the handle or the resource that the handle represents is exposed to untrusted code, this can lead to a recycling security attack on the reused or returned handle.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top