1

I found the following code in a Unity3D project using the Kinect v2 which I have taken over. I'm paranoid so I thought I'd check before I delete it. But surely there is no reason for these two lines??

colorFrame.Dispose();
colorFrame = null;

This is C#. It has automatic garbage collection so my understanding is that colorFrame will be disposed when its convenient outside of the if(GetRGB) statement

if (GetRGB)
{
    ColorFrame colorFrame = frame.ColorFrameReference.AcquireFrame ();
    if (colorFrame != null)
    {
        colorFrame.CopyConvertedFrameDataToArray (_ColorData, ColorImageFormat.Rgba);
        _ColorTexture.LoadRawTextureData (_ColorData);
        _ColorTexture.Apply ();
        colorFrame.Dispose ();
        colorFrame = null;
    }
}
Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321
Guye Incognito
  • 2,726
  • 6
  • 38
  • 72
  • possible duplicate of [Do you need to dispose of objects and set them to null?](http://stackoverflow.com/questions/2926869/do-you-need-to-dispose-of-objects-and-set-them-to-null) – Gerald Versluis Jun 04 '15 at 08:37

3 Answers3

4

It has automatic garbage collection so my understanding is that colorFrame will be disposed when its convenient outside of the if(GetRGB) statement

The object will be cleaned once that GC kicks in (at a non-deterministic time) and sees there is no root to the colorFrame object. Calling Dispose on an object usually releases unmanaged resources allocated by that same object, as well as calls GC.SupressFinalize, which makes any object that has a finalizer de-register from the finalization queue, allowing the GC to clean it up "faster".

I would suggest keeping the call to Dispose. I would remove the colorFrame = null call, which is useless.

Better yet, wrap colorFrame in a using statement:

if (GetRGB)
{
    using (ColorFrame colorFrame = frame.ColorFrameReference.AcquireFrame()) 
    {
        if (colorFrame != null)
        {
           colorFrame.CopyConvertedFrameDataToArray(_ColorData, ColorImageFormat.Rgba);
           _ColorTexture.LoadRawTextureData(_ColorData);
           _ColorTexture.Apply();
        }
    }
}
Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321
1

It will be garbage collected at a non-deterministic future time. If the class has been written correctly, it will include an internal call to Dispose.

However, you should always call Dispose (or better, use a using block) on IDisposable objects as that way they can release any unmanaged resources they are currently holding on to without waiting for the framework to perform a garbage collection.

James Thorpe
  • 31,411
  • 5
  • 72
  • 93
0

Garbage Collection is part of the CLR. IDisposable is an arbitrary interface that is used to clean on resources used by a class when it finishes its life. DON'T REMOVE DISPOSE!!! The framework knows nothing of Dipose() and won't call it.

James Lucas
  • 2,452
  • 10
  • 15