#31 Safe handle has been closed Exception

v2.2.8
open-duplicate
7
2014-08-21
2010-12-02
No

I'm getting the above exception with 2.2.8 (from UsbTransfer finalizer called from the GC); it looks as though it's caused by my UsbEndpointReader's TransferContext not being disposed. I've gone through the code and it seems like it's down to the way IDisposable has been implemented on some of the classes (so this may happen elsewhere). In your Finalizer you shouldn't access any members as, and is the case here (OverlappedTransferContext accesses UsbDevice.Handle (via OverlappedTransferContext->Wait()/UsbEndpointBase.Handle)) the member may already be disposed (you can't determine the order objects will be finalized).

Usually the pattern would be :

class x : IDisposable
{
private bool _disposed;

~x()
{
Dispose(false);
}

protected virtual void Dispose(bool disposing)
{
if(disposing && !_disposed)
{
_diposed = true;
/// do stuff here
}
}

void Dispose()
{
Dispose(true);
GC.SurpressFinalize(this);
}
}

Might just be quicker to dispose the context in UsbEndpointBase, but working in the finalizer is bound to cause problems sooner or later.

Discussion

  • Travis Robinson

    Travis Robinson - 2010-12-02

    Thanks for pointing this out. This was actually reported last week; I came to the same conclusion; that there were some issues in they way IDisposable was implemented in a few of the classes. :)

    The original report is here:
    https://sourceforge.net/tracker/?func=detail&atid=1140572&aid=3122105&group_id=206606

    Your tracker has more info, so I will keep them both. It should also notify when this issue is resolved.

    Thanks Again,
    Travis

     
  • Travis Robinson

    Travis Robinson - 2010-12-02
    • milestone: --> v2.2.8
    • priority: 5 --> 7
    • status: open --> open-duplicate
     
  • Chuck Gannon

    Chuck Gannon - 2014-04-15

    I am having a similar issue with our application.

    I have tried using the r113 release as well. I incorporated the code into our solution. If I disconnect our USB device and quickly reconnect, I get get exception in OverlappedTransferContext.cs in method Wait at line 97.

    The EndPointBase throwing the exception is always LibUsbDotNet.UsbEndpointWriter. The endpoint writer indicates it is already disposed and the EndpointBase.Handle indicates it is closed.

    If I dummy up the code and add a check for EndpointBase.Handle.IsClosed before calling GetOverlappedResult I can stop it from throwing. I'm guessing this is not the optimal solution. Also not sure if we are correctly closing everything when we detect disconnect (although our code follows the examples in the project).

    Any help you can provide would be appreciated. Thanks
    -Chuck

     

Log in to post a comment.

Get latest updates about Open Source Projects, Conferences and News.

Sign up for the SourceForge newsletter:





No, thanks