I've been having similar issues with a "Safe handle has been closed" ObjectDisposedException happening as I close my WPF application.
My stacktrace was slightly different:
System.ObjectDisposedException was unhandled
HResult=-2146232798
Message=Safe handle has been closed
Source=mscorlib
ObjectName=""
StackTrace:
at System.Threading.WaitHandle.WaitOneNative(SafeHandle waitableSafeHandle, UInt32 millisecondsTimeout, Boolean hasThreadAffinity, Boolean exitContext)
at System.Threading.WaitHandle.InternalWaitOne(SafeHandle waitableSafeHandle, Int64 millisecondsTimeout, Boolean hasThreadAffinity, Boolean exitContext)
at System.Threading.WaitHandle.WaitOne(Int32 millisecondsTimeout, Boolean exitContext)
at LibUsbDotNet.Main.UsbTransfer.get_IsCancelled()
at LibUsbDotNet.Main.UsbTransfer.Dispose()
at LibUsbDotNet.Main.UsbTransfer.Finalize()
InnerException:
I however, have managed to fix it by adding the following code to my transmit and receive functions..
using (UsbEndpointWriter writer = device.OpenEndpointWriter(WriteEndpoint))
{
UsbTransfer usbTransfer = null;
try
{
// Code to do transfer here .. not shown as not pertinent here..
}
finally
{
if (usbTransfer != null)
{
// **** Start of code added to fix ObjectDisposedException
if (!usbTransfer.IsCancelled || !usbTransfer.IsCompleted)
{
usbTransfer.Cancel();
}
// **** End of code added to fix ObjectDisposedException
usbTransfer.Dispose();
}
}
}
Hopefully, this snippet might help anyone else who finds this question whilst trying to fix their issue.