C # 2008

我已经在这方面工作了一段时间,但我仍然对在代码中使用finalize和dispose方法感到困惑。我的问题如下:

I know that we only need a finalizer while disposing unmanaged resources. However, if there are managed resources that make calls to unmanaged resources, would it still need to implement a finalizer? However, if I develop a class that doesn't use any unmanaged resource - directly or indirectly, should I implement the IDisposable to allow the clients of that class to use the 'using statement'? Would it be feasible to implement IDisposable just to enable clients of your class to use the using statement? using(myClass objClass = new myClass()) { // Do stuff here } I have developed this simple code below to demonstrate the Finalize/dispose use: public class NoGateway : IDisposable { private WebClient wc = null; public NoGateway() { wc = new WebClient(); wc.DownloadStringCompleted += wc_DownloadStringCompleted; } // Start the Async call to find if NoGateway is true or false public void NoGatewayStatus() { // Start the Async's download // Do other work here wc.DownloadStringAsync(new Uri(www.xxxx.xxx)); } private void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) { // Do work here } // Dispose of the NoGateway object public void Dispose() { wc.DownloadStringCompleted -= wc_DownloadStringCompleted; wc.Dispose(); GC.SuppressFinalize(this); } }

关于源代码的问题:

Here I have not added the finalizer, and normally the finalizer will be called by the GC, and the finalizer will call the Dispose. As I don't have the finalizer, when do I call the Dispose method? Is it the client of the class that has to call it? So my class in the example is called NoGateway and the client could use and dispose of the class like this: using(NoGateway objNoGateway = new NoGateway()) { // Do stuff here } Would the Dispose method be automatically called when execution reaches the end of the using block, or does the client have to manually call the dispose method? i.e. NoGateway objNoGateway = new NoGateway(); // Do stuff with object objNoGateway.Dispose(); // finished with it I am using the WebClient class in my NoGateway class. Because WebClient implements the IDisposable interface, does this mean that WebClient indirectly uses unmanaged resources? Is there a hard and fast rule to follow this? How do I know that a class uses unmanaged resources?


using(NoGateway objNoGateway = new NoGateway())

等于

try
{
    NoGateway = new NoGateway();
}

finally
{
    NoGateway.Dispose();
}

在GC销毁对象时调用终结器。这可能与你离开方法时完全不同。Dispose of IDisposable在你离开using块后立即被调用。因此,这种模式通常是在您不再需要资源后立即使用using来释放它们。

1) WebClient是一个托管类型,所以你不需要终结器。如果您的用户不Dispose()您的NoGateway类,并且本机类型(不被GC收集)之后需要清理,则需要结束器。在这种情况下,如果用户没有调用Dispose(),所包含的WebClient将在NoGateway调用之后被GC丢弃。

间接地,是的,但你不必担心。你的代码是正确的,你不能防止你的用户很容易忘记Dispose()。

推荐的IDisposable模式如下。当编程一个使用IDisposable的类时,通常你应该使用两种模式:

当实现一个不使用非托管资源的密封类时,你只需像普通接口实现一样实现Dispose方法:

public sealed class A : IDisposable
{
    public void Dispose()
    {
        // get rid of managed resources, call Dispose on member variables...
    }
}

当实现一个非密封类时,像这样做:

public class B : IDisposable
{    
    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    protected virtual void Dispose(bool disposing)
    {
        if (disposing)
        {
            // get rid of managed resources
        }   
        // get rid of unmanaged resources
    }

    // only if you use unmanaged resources directly in B
    //~B()
    //{
    //    Dispose(false);
    //}
}

注意,我没有在B中声明终结式;只有在有实际的非托管资源要处理时,才应该实现终结器。CLR处理可终结对象与处理不可终结对象是不同的,即使调用了SuppressFinalize。

所以,除非必须,否则你不应该声明终结器,但是你可以给类的继承者一个钩子来调用你的Dispose,如果他们直接使用非托管资源,他们自己实现终结器:

public class C : B
{
    private IntPtr m_Handle;

    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            // get rid of managed resources
        }
        ReleaseHandle(m_Handle);

        base.Dispose(disposing);
    }

    ~C() {
        Dispose(false);
    }
}

如果您没有直接使用非托管资源(SafeHandle和friend不计算在内,因为它们声明了自己的终结器),那么就不要实现终结器,因为GC以不同的方式处理可终结类,即使您稍后抑制了终结器。还要注意,即使B没有终结器,它仍然调用SuppressFinalize来正确处理任何实现了终结器的子类。

当一个类实现IDisposable接口时,这意味着在某个地方有一些非托管资源,当您使用完该类时,这些资源应该被删除。实际资源封装在类中;您不需要显式地删除它们。只需调用Dispose()或将类包装在using(…){}中,就可以确保在必要时删除任何非托管资源。

If you are using other managed objects that are using unmanaged resources, it is not your responsibility to ensure those are finalized. Your responsibility is to call Dispose on those objects when Dispose is called on your object, and it stops there. If your class doesn't use any scarce resources, I fail to see why you would make your class implement IDisposable. You should only do so if you're: Know you will have scarce resources in your objects soon, just not now (and I mean that as in "we're still developing, it will be here before we're done", not as in "I think we'll need this") Using scarce resources Yes, the code that uses your code must call the Dispose method of your object. And yes, the code that uses your object can use using as you've shown. (2 again?) It is likely that the WebClient uses either unmanaged resources, or other managed resources that implement IDisposable. The exact reason, however, is not important. What is important is that it implements IDisposable, and so it falls on you to act upon that knowledge by disposing of the object when you're done with it, even if it turns out WebClient uses no other resources at all.

据我所知,强烈建议不要使用终结器/析构函数:

public ~MyClass() {
  //dont use this
}

大多数情况下,这是因为不知道何时或是否会调用它。处置方法是更好的,特别是如果你使用或直接处置。

使用是好的。使用它:)

Note that any IDisposable implementation should follow the below pattern (IMHO). I developed this pattern based on info from several excellent .NET "gods" the .NET Framework Design Guidelines (note that MSDN does not follow this for some reason!). The .NET Framework Design Guidelines were written by Krzysztof Cwalina (CLR Architect at the time) and Brad Abrams (I believe the CLR Program Manager at the time) and Bill Wagner ([Effective C#] and [More Effective C#] (just take a look for these on Amazon.com:

Note that you should NEVER implement a Finalizer unless your class directly contains (not inherits) UNmanaged resources. Once you implement a Finalizer in a class, even if it is never called, it is guaranteed to live for an extra collection. It is automatically placed on the Finalization Queue (which runs on a single thread). Also, one very important note...all code executed within a Finalizer (should you need to implement one) MUST be thread-safe AND exception-safe! BAD things will happen otherwise...(i.e. undetermined behavior and in the case of an exception, a fatal unrecoverable application crash).

我把模式放在一起(并为其编写了代码片段)如下:

#region IDisposable implementation

//TODO remember to make this class inherit from IDisposable -> $className$ : IDisposable

// Default initialization for a bool is 'false'
private bool IsDisposed { get; set; }

/// <summary>
/// Implementation of Dispose according to .NET Framework Design Guidelines.
/// </summary>
/// <remarks>Do not make this method virtual.
/// A derived class should not be able to override this method.
/// </remarks>
public void Dispose()
{
    Dispose( true );

    // This object will be cleaned up by the Dispose method.
    // Therefore, you should call GC.SupressFinalize to
    // take this object off the finalization queue 
    // and prevent finalization code for this object
    // from executing a second time.

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

/// <summary>
/// Overloaded Implementation of Dispose.
/// </summary>
/// <param name="isDisposing"></param>
/// <remarks>
/// <para><list type="bulleted">Dispose(bool isDisposing) executes in two distinct scenarios.
/// <item>If <paramref name="isDisposing"/> equals true, the method has been called directly
/// or indirectly by a user's code. Managed and unmanaged resources
/// can be disposed.</item>
/// <item>If <paramref name="isDisposing"/> 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.</item></list></para>
/// </remarks>
protected virtual void Dispose( bool isDisposing )
{
    // TODO If you need thread safety, use a lock around these 
    // operations, as well as in your methods that use the resource.
    try
    {
        if( !this.IsDisposed )
        {
            if( isDisposing )
            {
                // TODO Release all managed resources here

                $end$
            }

            // TODO Release all unmanaged resources here



            // TODO explicitly set root references to null to expressly tell the GarbageCollector
            // that the resources have been disposed of and its ok to release the memory allocated for them.


        }
    }
    finally
    {
        // explicitly call the base class Dispose implementation
        base.Dispose( isDisposing );

        this.IsDisposed = true;
    }
}

//TODO Uncomment this code if this class will contain members which are UNmanaged
// 
///// <summary>Finalizer for $className$</summary>
///// <remarks>This finalizer will run only if the Dispose method does not get called.
///// It gives your base class the opportunity to finalize.
///// DO NOT provide finalizers in types derived from this class.
///// All code executed within a Finalizer MUST be thread-safe!</remarks>
//  ~$className$()
//  {
//     Dispose( false );
//  }
#endregion IDisposable implementation

下面是在派生类中实现IDisposable的代码。注意,您不需要在派生类的定义中显式地列出来自IDisposable的继承。

public DerivedClass : BaseClass, IDisposable (remove the IDisposable because it is inherited from BaseClass)


protected override void Dispose( bool isDisposing )
{
    try
    {
        if ( !this.IsDisposed )
        {
            if ( isDisposing )
            {
                // Release all managed resources here

            }
        }
    }
    finally
    {
        // explicitly call the base class Dispose implementation
        base.Dispose( isDisposing );
    }
}

我已经在我的博客上发布了这个实现:如何正确地实现Dispose模式

没有人回答你是否应该实现IDisposable的问题,即使你不需要它。

简单的回答:不

长一点的回答:

这将允许你的类的消费者使用“using”。我想问的问题是,他们为什么要这么做?大多数开发者不会使用“使用”,除非他们知道他们必须这么做——他们是怎么知道的。要么

很明显,从经验来看(例如,一个套接字类) 它的记录 他们很谨慎,可以看到类实现了IDisposable

因此,通过实现IDisposable,你可以告诉开发人员(至少是一些开发人员)这个类封装了一些必须发布的东西。他们会使用“using”——但在其他情况下,使用是不可能的(对象的作用域不是本地的);他们将不得不开始担心在其他情况下对象的生命周期-我肯定会担心。但这是不必要的

你实现Idisposable,让他们使用使用,但他们不会使用使用,除非你告诉他们。

所以不要这么做

我同意pm100的观点(我应该在之前的文章中明确地说明这一点)。

除非需要,否则永远不要在类中实现IDisposable。具体来说,大约有5次你需要/应该实现IDisposable:

Your class explicitly contains (i.e. not via inheritance) any managed resources which implement IDisposable and should be cleaned up once your class is no longer used. For example, if your class contains an instance of a Stream, DbCommand, DataTable, etc. Your class explicitly contains any managed resources which implement a Close() method - e.g. IDataReader, IDbConnection, etc. Note that some of these classes do implement IDisposable by having Dispose() as well as a Close() method. Your class explicitly contains an unmanaged resource - e.g. a COM object, pointers (yes, you can use pointers in managed C# but they must be declared in 'unsafe' blocks, etc. In the case of unmanaged resources, you should also make sure to call System.Runtime.InteropServices.Marshal.ReleaseComObject() on the RCW. Even though the RCW is, in theory, a managed wrapper, there is still reference counting going on under the covers. If your class subscribes to events using strong references. You need to unregister/detach yourself from the events. Always to make sure these are not null first before trying to unregister/detach them!. Your class contains any combination of the above...

对于使用COM对象并且必须使用Marshal.ReleaseComObject(),推荐的替代方法是使用System.Runtime.InteropServices.SafeHandle类。

BCL(基类库团队)在这里有一篇关于它的很好的博客文章http://blogs.msdn.com/bclteam/archive/2005/03/16/396900.aspx

一个非常重要的注意事项是,如果你正在使用WCF并清理资源,你几乎总是应该避免使用'using'块。有很多博客和MSDN上的文章都在解释为什么这是一个坏主意。我也在这里发布了关于它的帖子-不要在WCF代理中使用'using()'

实现IDisposable的官方模式很难理解。我认为这个更好:

public class BetterDisposableClass : IDisposable {

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

  protected virtual void CleanUpManagedResources() { 
    // ...
  }
  protected virtual void CleanUpNativeResources() {
    // ...
  }

  ~BetterDisposableClass() {
    CleanUpNativeResources();
  }

}

一个更好的解决方案是有一个规则,你总是必须为你需要处理的任何非托管资源创建一个包装器类:

public class NativeDisposable : IDisposable {

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

  protected virtual void CleanUpNativeResource() {
    // ...
  }

  ~NativeDisposable() {
    CleanUpNativeResource();
  }

}

对于SafeHandle及其衍生品,这些类应该非常少。

对于不直接处理非托管资源(即使存在继承)的一次性类,其结果是强大的:它们不再需要关心非托管资源。它们很容易实现和理解:

public class ManagedDisposable : IDisposable {

  public virtual void Dispose() {
    // dispose of managed resources
  }

}

来自msdn的模式

public class BaseResource: IDisposable
{
   private IntPtr handle;
   private Component Components;
   private bool disposed = false;
   public BaseResource()
   {
   }
   public void Dispose()
   {
      Dispose(true);      
      GC.SuppressFinalize(this);
   }
   protected virtual void Dispose(bool disposing)
   {
      if(!this.disposed)
      {        
         if(disposing)
         {
            Components.Dispose();
         }         
         CloseHandle(handle);
         handle = IntPtr.Zero;
       }
      disposed = true;         
   }
   ~BaseResource()      
   {      Dispose(false);
   }
   public void DoSomething()
   {
      if(this.disposed)
      {
         throw new ObjectDisposedException();
      }
   }
}
public class MyResourceWrapper: BaseResource
{
   private ManagedResource addedManaged;
   private NativeResource addedNative;
   private bool disposed = false;
   public MyResourceWrapper()
   {
   }
   protected override void Dispose(bool disposing)
   {
      if(!this.disposed)
      {
         try
         {
            if(disposing)
            {             
               addedManaged.Dispose();         
            }
            CloseHandle(addedNative);
            this.disposed = true;
         }
         finally
         {
            base.Dispose(disposing);
         }
      }
   }
}

另一个答案的某些方面有点不正确,原因有二:

首先,

using(NoGateway objNoGateway = new NoGateway())

Actually相当于:

try
{
    NoGateway = new NoGateway();
}
finally
{
    if(NoGateway != null)
    {
        NoGateway.Dispose();
    }
}

This may sound ridiculous since the 'new' operator should never return 'null' unless you have an OutOfMemory exception. But consider the following cases: 1. You call a FactoryClass that returns an IDisposable resource or 2. If you have a type that may or may not inherit from IDisposable depending on its implementation - remember that I've seen the IDisposable pattern implemented incorrectly many times at many clients where developers just add a Dispose() method without inheriting from IDisposable (bad, bad, bad). You could also have the case of an IDisposable resource being returned from a property or method (again bad, bad, bad - don't 'give away your IDisposable resources)

using(IDisposable objNoGateway = new NoGateway() as IDisposable)
{
    if (NoGateway != null)
    {
        ...

如果'as'操作符返回null(或返回资源的属性或方法),并且'using'块中的代码可以防止'null',那么在尝试对空对象调用Dispose时,您的代码不会因为'内置'空检查而崩溃。

你的回复不准确的第二个原因是由于以下stmt:

在GC销毁对象时调用终结器

First, Finalization (as well as GC itself) is non-deterministic. THe CLR determines when it will call a finalizer. i.e. the developer/code has no idea. If the IDisposable pattern is implemented correctly (as I've posted above) and GC.SuppressFinalize() has been called, the the Finalizer will NOT be called. This is one of the big reasons to properly implement the pattern correctly. Since there is only 1 Finalizer thread per managed process, regardless of the number of logical processors, you can easily degrade performance by backing up or even hanging the Finalizer thread by forgetting to call GC.SuppressFinalize().

我已经在我的博客上发布了Dispose模式的正确实现:如何正确地实现Dispose模式

使用lambdas代替IDisposable。

我从来没有对使用/IDisposable这个想法感到兴奋。问题是它要求调用者:

知道他们必须使用IDisposable 记住使用“using”。

我新的首选方法是使用工厂方法和lambda代替

假设我想用SqlConnection(应该用using包装的东西)做一些事情。通常你会这么做

using (Var conn = Factory.MakeConnection())
{
     conn.Query(....);
}

新方法

Factory.DoWithConnection((conn)=>
{
    conn.Query(...);
}

在第一种情况下,调用者不能简单地使用using语法。在第二种情况下,用户没有选择。没有创建SqlConnection对象的方法,调用者必须调用DoWithConnection。

DoWithConnection看起来像这样

void DoWithConnection(Action<SqlConnection> action)
{
   using (var conn = MakeConnection())
   {
       action(conn);
   }
}

MakeConnection现在是私有的

处理模式:

public abstract class DisposableObject : IDisposable
{
    public bool Disposed { get; private set;}      

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

    ~DisposableObject()
    {
        Dispose(false);
    }

    private void Dispose(bool disposing)
    {
        if (!Disposed)
        {
            if (disposing)
            {
                DisposeManagedResources();
            }

            DisposeUnmanagedResources();
            Disposed = true;
        }
    }

    protected virtual void DisposeManagedResources() { }
    protected virtual void DisposeUnmanagedResources() { }
}

继承的例子:

public class A : DisposableObject
{
    public Component components_a { get; set; }
    private IntPtr handle_a;

    protected override void DisposeManagedResources()
    {
        try
        {
          Console.WriteLine("A_DisposeManagedResources");
          components_a.Dispose();
          components_a = null;
        }
        finally
        { 
          base.DisposeManagedResources();
        }
    }

    protected override void DisposeUnmanagedResources()
    {
        try
        {
          Console.WriteLine("A_DisposeUnmanagedResources");
          CloseHandle(handle_a);
          handle_a = IntPtr.Zero;
        }
        finally
        { 
          base.DisposeUnmanagedResources();
        }
    }
}

public class B : A
{
    public Component components_b { get; set; }
    private IntPtr handle_b;

    protected override void DisposeManagedResources()
    {
        try
        {
          Console.WriteLine("B_DisposeManagedResources");
          components_b.Dispose();
          components_b = null;
        }
        finally
        { 
          base.DisposeManagedResources();
        }
    }

    protected override void DisposeUnmanagedResources()
    {
        try
        {
          Console.WriteLine("B_DisposeUnmanagedResources");
          CloseHandle(handle_b);
          handle_b = IntPtr.Zero;
        }
        finally
        { 
          base.DisposeUnmanagedResources();
        }
    }
}