简体   繁体   中英

Dispose of objects in user control?

I have a usercontrol that uses a DataSet objects. I would like to implement the IDisposable interface, however the usercontrol's designer class already has the following method:

    protected override void Dispose(bool disposing)
    {
        if (disposing && (components != null))
        {
            components.Dispose();
        }
        base.Dispose(disposing);
    }

How can I correctly dispose of my DataSet object?

You can call that once the control is disposed. Just subscribe to the Disposed event of the control and dispose your own classes inside.

overriden Dispose method is not a part of Component Designer generated code

so you can modify it

protected override void Dispose(bool disposing)
{
    if (disposing)
    {
        if (components != null)
            components.Dispose();
        System.Diagnostics.Debug.WriteLine("Dispose DataSet Here");
    }
    base.Dispose(disposing);
}

Easiest way to safely handle disposing the Dataset object, is putting it in a using clause:

using (DataSet ds = new DataSet())
{
        // Put code that adds stuff to DataSet here.
        // ... The DataSet will be cleaned up outside the block.
}

This way you don't have to manually dispose the DataSet object afterwards. It will be disposed when leaving the using block.

Using (MSDN)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM