views:

129

answers:

2

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

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

A: 

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.

Konamiman
Thanks for your answer, is there a better way to implement what I described?
pablito
+1  A: 

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.

Pent Ploompuu