CA2000: Dispose objects before losing scope/在退出作用域前Dispose object

如果一个类型实现了IDispose接口,但是在退出作用域前未Disposed/Close, 代码分析工具会提出警告:

CA2000: Dispose objects before losing scope

例如:

public string OpenPort1(string portName)
{
   SerialPort port = new SerialPort(portName); //SerialPort实现了IDispose接口
   port.Open();  //CA2000 fires because this might throw
   SomeMethod(); //Other method operations can fail
   return port.ToString();
}

如果SomeMethod出现异常,此类型也会安全释放未托管资源.如果用using包装,则不会有此警告.

public string OpenPort1(string portName)
{

   string result = string.Emtpy;
   using(SerialPort port = new SerialPort(portName))
   {

   port.Open();  //CA2000 fires because this might throw
   SomeMethod(); //Other method operations can fail,
   result = port.ToString();

   }

   return result;
}

当此类型作为返回值时,不能直接采用using来释放资源,如下例:

public SerialPort OpenPort1(string portName)

{

SerialPort port = new SerialPort(portName); port.Open(); //CA2000 fires because this might throw

SomeMethod(); //Other method operations can fail return port;

return port;

}

为避免操作中出现异常导致未托管资源未释放, 可采用try/finally包装代码,以保证在异常时资源安全释放,如下:

public SerialPort OpenPort2(string portName)
{
   SerialPort tempPort = null;
   SerialPort port = null;
   try
   {
      tempPort = new SerialPort(portName);
      tempPort.Open();
      SomeMethod();
      //Add any other methods above this line
      port = tempPort;
      tempPort = null;

   }
   finally
   {
      if (tempPort != null)
      {
         tempPort.Close();
      }
   }
   return port;
}

Detail See MSDN:CA2000: Dispose objects before losing scope

原文地址:https://www.cnblogs.com/zzj8704/p/1718798.html