• 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

  • 相关阅读:
    如何将平时所学的代码知识,用在实际测试场景中
    CSS,XTHML书写规范以及常见问题总结
    网页底部定位
    时不我待
    用CSS设置Table的细边框的最好用的方法
    CSS Hack总结说明
    批处理轻松删除Win7下WINDOWS.OLD文件夹
    通过iframe调用页面的一部分,实现自己想要的页面
    超简单的javascript
    form在IE6中会影响样式的问题
  • 原文地址:https://www.cnblogs.com/zzj8704/p/1718798.html
Copyright © 2020-2023  润新知