Grisson's .net

源码之前,了无秘密

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
The standard dispose idiom frees your unmanaged resorces using the IDisposable interface when clients remember,and it uses the finalizer defensively when clients forget.所以要为你的类添加 析构函数 以及 实现IDispose接口。

由于Finalizer是GC运行时自动执行的,虽然他的效率比较低,但它可以保证在你自定的类中占用的资源能被正确释放。

实现IDispose方法作为标准的方式去释放资源。一下是Dispose方法中要实现的4个任务:
1.Freeing all unmanaged resource
2.Freeing all managed resource
3.Setting a state flag to indicate that the object has been disposed.You need to check this state and throw ObjectDisposed 
 exception in you public methods,if any get called after disposing of an object.
4.Suppressing finalizaiton,是用GC.SuppressFinalizer(this);

为了子类能实现自己的Disopse方法,最好把父类Dispose的方法声明为virtual

If dispose called on an object that has already been disposed of, it does nothing.Finalizers have similar rules.

Do not perform any other processing during a dispose method. 会造成非常混乱的情况

e.g.
public class MyResourceHog : IDisposable
{
  
private bool _alreadyDisposed = false;

  
~MyResourceHog()
  
{
    Dispose(
true);
  }


  
public void Dispose()
  
{
    Dispose(
true);
    GC.SuppressFinalize(
this);
  }


  
public virtual void Dispose(bool isDisposing)
  
{
     
if(_alreadtDisposed)
        
return;
     
if(isDisposing)
     
{
       
//.
     }


     _alreadyDisposing 
= true;
  }

}


///////////////////////////////////////////

public class DeriveResuorceHog : MyResouceHog
{
  
private bool _disposed = false;
  
  
protected override void Dispose(bool isDisposing)
  
{
    
if(_dispose)
    
{
      
return;
    }

    
if(isDisposing)
    
{
      
//
    }


    
base.Dispose(isDisposing);
    _disposed 
= true;
  }

}
posted on 2005-08-16 10:06  海盗  阅读(312)  评论(0编辑  收藏  举报