开发者

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?

  1. pBar.Dispose();
  2. pBar = null;
  3. 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜