sharpdx / SharpDX

SharpDX GitHub Repository
http://sharpdx.org
MIT License
1.69k stars 641 forks source link

DeviceChild not untracking Device in ObjectTracker #973

Open ziriax opened 6 years ago

ziriax commented 6 years ago

It seems that getting the Device from a DeviceChild adds the Device to the ObjectTracker, but Disposing the DeviceChild just releases the Device, so it is not untracked by the ObjectTracker.

Is this intentional, or a minor bug?

Just setting the __Device.NativePointer to zero after releasing the device seems to fix this.

Nope, the above fixes the problem, but causes memory leaks, because when creating a Device, the following code doesn't create a new device wrapper, but just links the Device with its DeviceContexts:

 if (ImmediateContext__ != null)
            {
                // Add a reference when setting the device on the context
                ((IUnknown)this).AddReference();
                ImmediateContext__.Device__ = this;
            }

Same for the DeferredContext. Is this an optimization? Because getting the Device property from any DeviceChild will create a managed wrapper lazily, once, so IMHO the above code might not be needed, although it does save some cycles and memory.

This also explains the following comment in DeviceChild:

      private void DisposeDevice()
        {
            if (Device__ != null)
            {
                // Don't use Dispose() in order to avoid circular references with DeviceContext
                ((IUnknown)Device__).Release();

                Device__ = null;
            }
        }

This could just become a dispose call when the Device__ poking code is removed