Rocho.J

人脑是不可靠的, 随时记录感悟并且经常重复!

 

[转] C#中标准Dispose模式的实现 --- 转自 http://guojun2sq.blog.163.com/blog/static/6433086120113982749792/

 

需要明确一下C#程序(或者说.NET)中的资源。简单的说来,C#中的每一个类型都代表一种资源,而资源又分为两类:

托管资源:由CLR管理分配和释放的资源,即由CLR里new出来的对象;

非托管资源:不受CLR管理的对象,windows内核对象,如文件、数据库连接、套接字、COM对象等;

毫无例外地,如果我们的类型使用到了非托管资源,或者需要显式释放的托管资源,那么,就需要让类型继承接口IDisposable。这相当于是告诉调用者,该类型是需要显式释放资源的,你需要调用我的Dispose方法。

不过,这一切并不这么简单,一个标准的继承了IDisposable接口的类型应该像下面这样去实现。这种实现我们称之为Dispose模式:

publicclass SampleClass : IDisposable
{
//演示创建一个非托管资源
private IntPtr nativeResource = Marshal.AllocHGlobal(100);
//演示创建一个托管资源
private AnotherResource managedResource =new AnotherResource();
privatebool disposed =false;

///<summary>
/// 实现IDisposable中的Dispose方法
///</summary>
publicvoid Dispose()
{
//必须为true
Dispose(true);
//通知垃圾回收机制不再调用终结器(析构器)
GC.SuppressFinalize(this);
}

///<summary>
/// 不是必要的,提供一个Close方法仅仅是为了更符合其他语言(如C++)的规范
///</summary>
publicvoid Close()
{
Dispose();
}

///<summary>
/// 必须,以备程序员忘记了显式调用Dispose方法
///</summary>
~SampleClass()
{
//必须为false
Dispose(false);
}

///<summary>
/// 非密封类修饰用protected virtual
/// 密封类修饰用private
///</summary>
///<param name="disposing"></param>
protectedvirtualvoid Dispose(bool disposing)
{
if (disposed)
{
return;
}
if (disposing)
{
// 清理托管资源
if (managedResource !=null)
{
managedResource.Dispose();
managedResource
=null;
}
}
// 清理非托管资源
if (nativeResource != IntPtr.Zero)
{
Marshal.FreeHGlobal(nativeResource);
nativeResource
= IntPtr.Zero;
}
//让类型知道自己已经被释放
disposed =true;
}

publicvoid SamplePublicMethod()
{
if (disposed)
{
thrownew ObjectDisposedException("SampleClass", "SampleClass is disposed");
}
//省略
}
}

在Dispose模式中,几乎每一行都有特殊的含义。

在标准的Dispose模式中,我们注意到一个以~开头的方法:

///<summary>
/// 必须,以备程序员忘记了显式调用Dispose方法
///</summary>
~SampleClass()
{
//必须为false
Dispose(false);
}

这个方法叫做类型的终结器。提供终结器的全部意义在于:我们不能奢望类型的调用者肯定会主动调用Dispose方法,基于终结器会被垃圾回收器调用这个特点,终结器被用做资源释放的补救措施。

一个类型的Dispose方法应该允许被多次调用而不抛异常。鉴于这个原因,类型内部维护了一个私有的布尔型变量disposed:

        private bool disposed = false;

在实际处理代码清理的方法中,加入了如下的判断语句:

if (disposed)
{
return;
}
//省略清理部分的代码,并在方法的最后为disposed赋值为true
disposed =true;

这意味着类型如果被清理过一次,则清理工作将不再进行。

应该注意到:在标准的Dispose模式中,真正实现IDisposable接口的Dispose方法,并没有实际的清理工作,它实际调用的是下面这个带布尔参数的受保护的虚方法:

///<summary>
/// 非密封类修饰用protected virtual
/// 密封类修饰用private
///</summary>
///<param name="disposing"></param>
protectedvirtualvoid Dispose(bool disposing)
{
//省略代码
}

之所以提供这样一个受保护的虚方法,是为了考虑到这个类型会被其他类继承的情况。如果类型存在一个子类,子类也许会实现自己的Dispose模式。受保护的虚方法用来提醒子类必须在实现自己的清理方法的时候注意到父类的清理工作,即子类需要在自己的释放方法中调用base.Dispose方法。

还有,我们应该已经注意到了真正撰写资源释放代码的那个虚方法是带有一个布尔参数的。之所以提供这个参数,是因为我们在资源释放时要区别对待托管资源和非托管资源。

在供调用者调用的显式释放资源的无参Dispose方法中,调用参数是true:

publicvoid Dispose()
{
//必须为true
Dispose(true);
//其他省略
}

这表明,这个时候代码要同时处理托管资源和非托管资源。

在供垃圾回收器调用的隐式清理资源的终结器中,调用参数是false:

~SampleClass()
{
//必须为false
Dispose(false);
}

这表明,隐式清理时,只要处理非托管资源就可以了。

那么,为什么要区别对待托管资源和非托管资源。在认真阐述这个问题之前,我们需要首先弄明白:托管资源需要手动清理吗?不妨先将C#中的类型分为两类,一类继承了IDisposable接口,一类则没有继承。前者,我们暂时称之为非普通类型,后者我们称之为普通类型。非普通类型因为包含非托管资源,所以它需要继承IDisposable接口,但是,这个包含非托管资源的类型本身,它是一个托管资源。所以说,托管资源需要手动清理吗?这个问题的答案是:托管资源中的普通类型,不需要手动清理,而非普通类型,是需要手动清理的(即调用Dispose方法)。

Dispose模式设计的思路基于:如果调用者显式调用了Dispose方法,那么类型就该按部就班为自己的所以资源全部释放掉。如果调用者忘记调用Dispose方法,那么类型就假定自己的所有托管资源(哪怕是那些上段中阐述的非普通类型)全部交给垃圾回收器去回收,而不进行手工清理。理解了这一点,我们就理解了为什么Dispose方法中,虚方法传入的参数是true,而终结器中,虚方法传入的参数是true。

 

注意:我们提到了需要及时释放资源,却并没有进一步细说是否需要及时让引用等于null这一点。有一些人认为等于null可以帮助垃圾回收机制早点发现并标识对象是垃圾。其他人则认为这没有任何帮助。

 

有一些人认为等于null可以帮助垃圾回收机制早点发现并标识对象是垃圾。其他人则认为这没有任何帮助。是否赋值为null的问题首先在方法的内部被人提起。现在,为了更好的阐述提出的问题,我们来撰写一个Winform窗体应用程序。如下:

privatevoid button1_Click(object sender, EventArgs e)
{
Method1();
Method2();
}

privatevoid button2_Click(object sender, EventArgs e)
{
GC.Collect();
}

privatevoid Method1()
{
SimpleClass s
=new SimpleClass("method1");
s
=null;
//其它无关工作代码(这条注释源于回应回复的朋友的质疑)
}
privatevoid Method2()
{
SimpleClass s
=new SimpleClass("method2");
}
}

class SimpleClass
{
string m_text;

public SimpleClass(string text)
{
m_text
= text;
}

~SimpleClass()
{
MessageBox.Show(
string.Format("SimpleClass Disposed, tag:{0}", m_text));
}
}

先点击按钮1,再点击按钮2释放,我们会发现:

q 方法Method2中的对象先被释放,虽然它在Method1之后被调用;

q 方法Method2中的对象先被释放,虽然它不像Method1那样为对象引用赋值为null;

在CLR托管应用程序中,存在一个“根”的概念,类型的静态字段、方法参数以及局部变量都可以作为“根”存在(值类型不能作为“根”,只有引用类型的指针才能作为“根”)。

上面的两个方法中各自的局部变量,在代码运行过程中会在内存中各自创建一个“根”.在一次垃圾回收中,垃圾回收器会沿着线程栈上行检查“根”。检查到方法内的“根”时,如果发现没有任何一个地方引用了局部变量,则不管是否为变量赋值为null,都意味着该“根”已经被停止掉。然后垃圾回收器发现该根的引用为空,同时标记该根可被释放,这也表示着Simple类型对象所占用的内存空间可被释放。所以,在上面的这个例子中,为s指定为null丝毫没有意义(方法的参数变量也是这种情况)。

更进一步的事实是,JIT编译器是一个经过优化的编译器,无论我们是否在方法内部为局部变量赋值为null,该语句都会被忽略掉

s = null;

在我们将项目设置为Release模式下,上面的这行代码将根本不会被编译进运行时内。

正式由于上面这样的分析,很多人认为为对象赋值为null完全没有必要。但是,在另外一种情况下,却要注意及时为变量赋值为null。那就是类型的静态字段。为类型对象赋值为null,并不意味着同时为类型的静态字段赋值为null:

privatevoid button1_Click(object sender, EventArgs e)
{
SimpleClass s
=new SimpleClass("test");
}

privatevoid button2_Click(object sender, EventArgs e)
{
GC.Collect();
}
}

class SimpleClass
{
static AnotherSimpleClass asc =new AnotherSimpleClass();
string m_text;

public SimpleClass(string text)
{
m_text
= text;
}

~SimpleClass()
{
//asc = null;
MessageBox.Show(string.Format("SimpleClass Disposed, tag:{0}", m_text));
}
}

class AnotherSimpleClass
{
~AnotherSimpleClass()
{
MessageBox.Show(
"AnotherSimpleClass Disposed");
}
}

以上代码运行的结果使我们发现,当执行垃圾回收,当类型SampleClass对象被回收的时候,类型的静态字段asc并没有被回收。

必须要将SimpleClass的终结器中注释的那条代码启用。

字段asc才能被正确释放(注意,要点击两次释放按钮。这是因为一次垃圾回收会仅仅首先执行终结器)。之所以静态字段不被释放(同时赋值为null语句也不会像局部变量那样被运行时编译器优化掉),是因为类型的静态字段一旦被创建,该“根”就一直存在。所以垃圾回收器始终不会认为它是一个垃圾。非静态字段不存在这个问题。将asc改为非静态,再次运行上面的代码,会发现asc随着类型的释放而被释放。

上文代码的例子中,让asc=null是在终结器中完成的,实际工作中,一旦我们感觉到自己的静态引用类型参数占用内存空间比较大,并且使用完毕后不再使用,则可以立刻将其赋值为null。这也许并不必要,但这绝对是一个好习惯。试想一下在一个大系统中,那些时不时在类型中出现的静态变量吧,它们就那样静静地呆在内存里,一旦被创建,就永远不离开,越来越多,越来越多……

 

 

 

=-======================================

转自MSDN

 

using System;
using System.IO;

class Program
{

    static void Main()
    {
        try
        {
            // Initialize a Stream resource to pass 
            // to the DisposableResource class.
            Console.Write("Enter filename and its path: ");
            string fileSpec = Console.ReadLine();
            FileStream fs = File.OpenRead(fileSpec);
            DisposableResource TestObj = new DisposableResource(fs);

            // Use the resource.
            TestObj.DoSomethingWithResource();

            // Dispose the resource.
            TestObj.Dispose();

        }
        catch (FileNotFoundException e)
        {
            Console.WriteLine(e.Message);
        }
    }
}


// This class shows how to use a disposable resource.
// The resource is first initialized and passed to
// the constructor, but it could also be
// initialized in the constructor.
// The lifetime of the resource does not 
// exceed the lifetime of this instance.
// This type does not need a finalizer because it does not
// directly create a native resource like a file handle
// or memory in the unmanaged heap.

public class DisposableResource : IDisposable
{

    private Stream _resource;  
    private bool _disposed;

    // The stream passed to the constructor 
    // must be readable and not null.
    public DisposableResource(Stream stream)
    {
        if (stream == null)
            throw new ArgumentNullException("Stream in null.");
        if (!stream.CanRead)
            throw new ArgumentException("Stream must be readable.");

        _resource = stream;

        _disposed = false;
    }

    // Demonstrates using the resource. 
    // It must not be already disposed.
    public void DoSomethingWithResource() {
        if (_disposed)
            throw new ObjectDisposedException("Resource was disposed.");

        // Show the number of bytes.
        int numBytes = (int) _resource.Length;
        Console.WriteLine("Number of bytes: {0}", numBytes.ToString());
    }


    public void Dispose() 
    {
        Dispose(true);

        // Use SupressFinalize in case a subclass
        // of this type implements a finalizer.
        GC.SuppressFinalize(this);      
    }

    protected virtual void Dispose(bool disposing)
    {
        // If you need thread safety, use a lock around these 
        // operations, as well as in your methods that use the resource.
        if (!_disposed)
        {
            if (disposing) {
                if (_resource != null)
                    _resource.Dispose();
                    Console.WriteLine("Object disposed.");
            }

            // Indicate that the instance has been disposed.
            _resource = null;
            _disposed = true;   
        }
    }
}

 

 

 ====================

using System;

namespace Demo
{
    // Design pattern for the base class.  
    // By implementing IDisposable, you are announcing that instances  
    // of this type allocate scarce resources.  
    public class BaseResource : IDisposable
    {
        // Pointer to an external unmanaged resource.  
        private IntPtr handle;
        // Other managed resource this class uses.  
        private Component Components;
        // Track whether Dispose has been called.  
        private bool disposed = false;
        // Constructor for the BaseResource object.  
        public BaseResource()
        {
            // Insert appropriate constructor code here.  
        }

        // Implement IDisposable. 
        // Do not make this method virtual. 
        // A derived class should not be able to override this method.  
        public void Dispose()
        {
            Dispose(true);
            // Take yourself off the Finalization queue 
            // to prevent finalization code for this object 
            // from executing a second time. 
            GC.SuppressFinalize(this);
        }
        // Dispose(bool disposing) executes in two distinct scenarios.  
        // If disposing equals true, the method has been called directly  
        // or indirectly by a user's code. Managed and unmanaged resources  
        // can be disposed.  
        // If disposing equals false, the method has been called by the   
        // runtime from inside the finalizer and you should not reference  
        // other objects. Only unmanaged resources can be disposed.  
        protected virtual void Dispose(bool disposing)
        {
            // Check to see if Dispose has already been called.  
            if (!this.disposed)
            {
                // If disposing equals true, dispose all managed   
                // and unmanaged resources. 
                if (disposing)
                {
                    // Dispose managed resources.  
                    Components.Dispose();
                }
                // Release unmanaged resources. If disposing is false,  
                // only the following code is executed.  
                CloseHandle(handle);
                handle = IntPtr.Zero;
                // Note that this is not thread safe. 
                // Another thread could start disposing the object  
                // after the managed resources are disposed,  
                // but before the disposed flag is set to true.  
                // If thread safety is necessary, it must be  
                // implemented by the client. 
            }
            disposed = true;
        }

        private void CloseHandle(IntPtr handle)
        {
            throw new NotImplementedException();
        }
        // Use C# destructor syntax for finalization code.
        // This destructor will run only if the Dispose method   
        // does not get called.  
        // It gives your base class the opportunity to finalize.  
        // Do not provide destructors in types derived from this class. 
        ~BaseResource()
        {
            // Do not re-create Dispose clean-up code here.
            // Calling Dispose(false) is optimal in terms of  
            // readability and maintainability.  
            Dispose(false);
        }
        // Allow your Dispose method to be called multiple times,  
        // but throw an exception if the object has been disposed.  
        // Whenever you do something with this class,   
        // check to see if it has been disposed.  
        public void DoSomething()
        {
            if (this.disposed)
            {
                throw new ObjectDisposedException();
            }
        }
    }
    // Design pattern for a derived class. 
    // Note that this derived class inherently implements the   
    // IDisposable interface because it is implemented in the base class.  
    public class MyResourceWrapper : BaseResource
    {
        // A managed resource that you add in this derived class.  
        private ManagedResource addedManaged;
        // A native unmanaged resource that you add in this derived class.  
        private NativeResource addedNative;
        private bool disposed = false;
        // Constructor for this object.  
        public MyResourceWrapper()
        {
            // Insert appropriate constructor code here.
        }
        protected override void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                try
                {
                    if (disposing)
                    {
                        // Release the managed resources you added in  
                        // this derived class here. 
                        addedManaged.Dispose();
                    }
                    // Release the native unmanaged resources you added  
                    // in this derived class here.  
                    CloseHandle(addedNative);
                    this.disposed = true;
                }
                finally
                {
                    // Call Dispose on your base class.  
                    base.Dispose(disposing);
                }
            }
        }

        private void CloseHandle(NativeResource addedNative)
        {
            throw new NotImplementedException();
        }
    }
}
// This derived class does not have a Finalize method 
// or a Dispose method without parameters because it inherits   
// them from the base class.  

 

 

posted on 2012-07-31 14:01  RJ  阅读(225)  评论(0编辑  收藏  举报

导航