0

.NET 中一直让我感到困惑的一个领域就是何时实现 IDisposable 模式。

我使用 WSDL 创建了一个 SOAP Web 服务代理,它在 Component 基类上实现了 IDisposable:

public partial class WSDLGeneratedProxy : System.Web.Services.Protocols.SoapHttpClientProtocol

我用简化的方法创建了某种外观接口,以便我可以隐藏服务代理交互,并使其实现 IDisposable:

public interface IServiceClient : IDisposable

我有 IServiceClient 的实现,并且该实现包含 WSDLGeneratedProxy 的实际成员

public class FacadeServiceClient : IServiceClient
{
    private WSDLGeneratedProxy clientProxy;
}

所以我的问题是 - 我应该显式调用服务代理上的 Dispose 方法吗?这是正确的方法吗?

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

protected virtual void Dispose(bool disposing)
{
    if (disposing)
    {
        if (clientProxy != null)
        {
            clientProxy.Dispose();
        }
    }
}

非常感谢任何建议或意见。

4

1 回答 1

-1

我看不出有任何理由必须处置该对象,无论如何,当不再使用它时,它都会被垃圾收集。

IDisposable 接口的基本用途是处置非托管对象(检查正确使用 IDisposable 接口

这就是我们使用using例如 System.IO 类的原因FileStream

      using (var fs = new FileStream(filePath, mode)) 
       {
              //use fs 
       }

当编译器遇到using关键字时,它会将代码重写为类似

        FileStream fs = new FileStream(filePath, mode); 
        try 
        {
            //use fs
         }
        finally 
        {
            //compiler will automatically call dispose on the FileStream to free up unmanaged objects
             fs.Dispose(); 
         }

当您处理内存中的大对象(例如数百 MB)并且不希望等待 GC 收集它们而是更早地收集它们时,您可能还想使用 dispose。

如果您不处于上述任何一种情况,那么 GC 在处理对象方面肯定会比您做的更好。

于 2013-11-06T23:17:44.827 回答