Quantcast
Channel: Common Language Runtime Internals and Architecture forum
Viewing all articles
Browse latest Browse all 1710

Types that own native resources should be disposable error - how to clear

$
0
0
I have a project with this class, which stores information about a WinUsb device:
internal class DeviceInfo {  internal SafeFileHandle deviceHandle;        internal IntPtr winUsbHandle;        internal Byte bulkInPipe;        internal Byte bulkOutPipe;        internal Byte interruptInPipe;        internal Byte interruptOutPipe;        internal UInt32 deviceSpeed;}        
Doing Build > Run code analysis results in this message:

CA1049 Types that own native resources should be disposable
Implement IDisposable on 'WinUsbDevice.DeviceInfo'.
WinUsb_cs - WinUsbDevice.cs (Line 30)

Following the example here:

http://msdn.microsoft.com/en-us/library/ms182173.aspx

I replaced the DeviceInfo class above with:

public class UnmanagedResources : IDisposable
{    public class DeviceInfo    {        internal SafeFileHandle DeviceHandle;        internal IntPtr WinUsbHandle;        internal Byte BulkInPipe;        internal Byte BulkOutPipe;        internal Byte InterruptInPipe;        internal Byte InterruptOutPipe;        internal UInt32 DeviceSpeed;    }    bool disposed = false;     public UnmanagedResources()    {        // Allocate the unmanaged resource ...                            }     public void Dispose()    {        Dispose(true);        GC.SuppressFinalize(this);    }     protected virtual void Dispose(bool disposing)    {        if (!disposed)        {            if (disposing)            {                // Release managed resources.            }             // Free the unmanaged resource ...                                 disposed = true;        }    }     ~UnmanagedResources()    {        Dispose(false);    }
}
Am I on the right track, and if so, how do I:

Allocate the unmanaged resource

and

Free the unmanaged resource

to clear the error message?

Additional information:

The code above is in my solution's WinUsbCommunications class.

In my FrmMain class, I create a DeviceInfo object:

private WinUsbCommunications.UnmanagedResources.DeviceInfo _myDeviceInfo = new WinUsbCommunications.UnmanagedResources.DeviceInfo();
Other code in FrmMain passes _myDeviceInfo in calls to WinUsbCommunications functions that access the WinUsb device.


Viewing all articles
Browse latest Browse all 1710

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>