代码如下:namespace logistics.EntityDAO
{
 /// <summary>
 /// ProductTypeEntityDAO的摘要说明。
 /// </summary>
 public class ProductTypeEntityDAO: IEntityDAO
 {
  //private static EntityData EntityPrototype=null;
  private DBCommon db;
  public ProductTypeEntityDAO()
  {
   db=new DBCommon();
   db.Open();
  }
 
  public ProductTypeEntityDAO(DBCommon cdb)
  {
   this.db=cdb;
  }  public void Dispose()
  {
   Dispose(true);
   GC.SuppressFinalize(true);
  }  protected virtual void Dispose(bool disposing)
  {
   if (! disposing)
    return; // we're being collected, so let the GC take care of this object
   db.Close();
  }
 }
} 以前给的在那里也坚果类似的写法,像这种方法对象建立的时候自动建立连接,而连接的释放却要等到对象被销毁的时候才会释放,这段时间是否会一只占用连接?再加上垃圾收集器是系统控制的GC.SuppressFinalize(true);是乎没有实际的意义只是做一个标记而已。像上面的这种写法适合在哪些情况下使用?

解决方案 »

  1.   

    有意义
    使用的时候用
     using(ProductTypeEntityDAO xxx=new ProductTypeEntityDAO())
    {
       xxx.
       }    
    这样using结束就会自动释放
      

  2.   

    这种对象一般都是通过using来调用的,会自动在using完后就自动调用dispose方法清除连接。不会出现一直占着连接的情况using(ProductTypeEntityDAO dao = new ProductTypeEntityDAO())
    {
       ///使用类
    }
    //到这里,dispose方法机已经执行了,连接已经处理了
      

  3.   

    再问:
       if (! disposing)
        return; // we're being collected, so let the GC take care of this object这句的作用是什么?好像没有意义,是否是如果这时GC以近启动了db在这时就已经被释放掉了,所以不再需要db.Close()??