Perhaps my question shows a lack of understanding in how IDisposible works, but I have a collection of class objects that manage communication with HID devices, each type has its own logic for detecting when the HID device is no longer active or communicating and will dispose of itself, but I would also like the class object to be removed from my ObservableCollection that stores all of them on its disposal.
Since this is a threaded environment im having a hard time picturing a way to implement a solution that wouldn't face race conditions.
Google so far has only yielded solutions to the opposite situation (dispose an object on removal from list).
Is it as simple as this?
#region IDisposable Support
private bool disposedValue = false; // To detect redundant calls
protected virtual void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
{
_hdevice.CancelIO();
_hdevice.CloseDevice();
_hdevice.Dispose();
}
// TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.
// TODO: set large fields to null.
//Remove device from its collection
lock (DeviceEnumerator.Devices)
{
DeviceEnumerator.Devices.Remove(this);
}
disposedValue = true;
}
}
// TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources.
// ~Dualshock4() {
// // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
// Dispose(false);
// }
// This code added to correctly implement the disposable pattern.
public void Dispose()
{
// Do not change this code. Put cleanup code in Dispose(bool disposing) above.
Dispose(true);
// TODO: uncomment the following line if the finalizer is overridden above.
// GC.SuppressFinalize(this);
}
#endregion