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)?
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.