Context: My situation is that I have to use an externally written native library from a managed .net environment. This native library sends messages realtime to my application at small intervals. It is expected from my application to respond within a certain amount of time. When this requirement is not met the situation is recoverable, but it does make the application slow for the user. There were many reaction speed issues which were all solved by adding an AutoResetEvent event in combination with a thread waiting for it.
The problem: The libary exposes a method through which I can pass a pointer to a handle from an AutoResetEvent. I pass this handle as an uint.
var handle = resetEvent.SafeWaitHandle.DangerousGetHandle();
var pointer = (uint)handle.ToInt32();
SetParameterValue(channel, param, pointer, 4);
And this handle is passed to the following method:
[DllImport("PCANBasic.dll", EntryPoint = "CAN_SetValue")]
private static extern NativeCanStatus SetParameterValue(
ushort Channel,
byte Parameter,
uint Handle,
uint BufferLength);
Everything seems to work great. However I did just write some code I do not understand the internal workings of. The name DangerousGetHandle is not really assuring. When the application is closed I set the parameter to a null-pointer, however I can not guarantee in the event of an application crash that I will set this paramater to a null-pointer. It seems to not cause any issues, but I do not understand why it doesn't give me any issues.
So, how unsafe is passing the DangerousHandle of an AutoResetEvent to a native library? Can the native library after an application failure keep calling something at this pointer? Or is this perfectly fine?