Should I Dispose() DataSet and DataTable?

前端 未结 12 1362
清酒与你
清酒与你 2020-11-22 02:45

DataSet and DataTable both implement IDisposable, so, by conventional best practices, I should call their Dispose() methods.

However, from what I\'ve read so far, Da

12条回答
  •  自闭症患者
    2020-11-22 02:50

    Even if an object has no unmanaged resources, disposing might help GC by breaking object graphs. In general, if an object implements IDisposable, Dispose() should be called.

    Whether Dispose() actually does something or not depends on the given class. In case of DataSet, Dispose() implementation is inherited from MarshalByValueComponent. It removes itself from container and calls Disposed event. The source code is below (disassembled with .NET Reflector):

    protected virtual void Dispose(bool disposing)
    {
        if (disposing)
        {
            lock (this)
            {
                if ((this.site != null) && (this.site.Container != null))
                {
                    this.site.Container.Remove(this);
                }
                if (this.events != null)
                {
                    EventHandler handler = (EventHandler) this.events[EventDisposed];
                    if (handler != null)
                    {
                        handler(this, EventArgs.Empty);
                    }
                }
            }
        }
    }
    

提交回复
热议问题