When NOT to use SafeHandles? -
04-03-2007
, 11:54 AM
Hi,
I use PInvoke interop to call the Win32 multi media Midi functions
(midiXxxxx). This API uses a handle for an open Midi in or out port
(device). I also use a callback function to get notified of opening
and closing of the port and of incoming midi data or when sending midi
data has finished.
Initialy I just used an Int32 to represent the handle, but then I read
about SafeHandles and I refactored my code to use them. I derived my
own classes to use the midiOutClose or midiInClose when closing the
handle.
The reason why I started doubting this solution is when I found that
when I leaked a midi port (on purpose), the SafeHandle is closed
correctly. But that also triggers a callback to my delegate that might
already be garbage-collected. I fear that by using SafeHandles I've
actually made my code less robust (in an other area).
Is this a scenario where SafeHandles are not a good idea? Or are
SafeHandles always a good idea and do I have to fix this callback-
issue seperatly? And is there a standard way to solve this callback
issue?
Any advice would be most welcome.
Grtx,
--Marc Jacobi |