Sunday, 9 March 2014

C# Dispose Method

Many classes have a method called Dispose(). The Dispose method is used to clear the class from memory. Some classes do not have dispose methods, this is usually because they don't have any properties that stay in memory. A link data class like the Form1DataContext class can load a lot of data into memory when it is used so it is good practice to dispose of it as soon as you no longer need it.

protected void ButtonSubmit_Click(object sender, EventArgs e)
{
Form1DataContext Data = new Form1DataContext();//This creates a new instance of the Form1DataContext class called Data. 
Data.SubmitChanges();// This method is just an example of a method that you might call from the Data instance.
Data.Dispose();//This will remove the Data instance from memory.
}
Note that If you try to work with the Data instance after Data.Dispose(); line you would cause an exception.

As well as disposing of instances using the Dispose method you can use a using statement to automatically dispose of an instance.
Note that working with using statements inside your code is different to the using statements at the top of your page.

protected void ButtonSubmit_Click(object sender, EventArgs e)
{
using(Form1DataContext Data = new Form1DataContext())//This creates a new instance of the Form1DataContext class called Data. 
{
Data.SubmitChanges();// This method is just an example of a method that you might call from the Data instance.
}
}

This does exactly the same thing as calling the Dispose method but is much easier to understand and work with. The using statement creates the Data instance and then automatically disposes of it after the last curly bracket.
Note that C# has a garbage collector that automatically disposes of objects that are no longer in scope. In this case for example the C# garbage collector would always dispose of the data instance after the ButtonSubmit_Click event handler was finished since it wouldn't be usable anymore. Despite this it is always best to dispose of instances where possible since the garbage collector doesn't always clean up memory immediately.

No comments:

Post a Comment