dispose resource in C#
ProgressBar pBar = new ProgressBar(obj);
if(_FileRead!=false)
{
pBar.Text = langSupport.Get开发者_开发百科Messages("123", cultureName);
pBar.ShowDialog();
}
In this example how I can dispose "pBar" resource. Below I have specifide 3 ways, which is the best way of object dispose?
pBar.Dispose();
pBar = null;
pBar.Dispose();
pBar = null;
Wrap the creation of the ProgressBar
in a using
statement.
using(ProgressBar pBar = new ProgressBar(obj))
{
if(_FileRead!=false)
{
pBar.Text = langSupport.GetMessages("123", cultureName);
pBar.ShowDialog();
}
}
Since it implements IDisposable
, this is the best way to ensure proper disposal.
If it supports it I would use:
using(ProgressBar pBar = new ProgressBar(obj))
{
if(_FileRead!=false)
{
pBar.Text = langSupport.GetMessages("123", cultureName);
pBar.ShowDialog();
}
}
In that way when it exits the using it disposes of all the relevant objects.
精彩评论