简体   繁体   English

我需要使用IDisposable吗?

[英]Do I need to use IDisposable?

Trying to see if I'm understanding this correctly. 尝试查看我是否正确理解了这一点。 Regretfully, I have not had much experience with IDisposable. 遗憾的是,我没有使用IDisposable的丰富经验。 We're taking a static class and making it non-static, and it's a class that is responsible for making web service calls in our Xamarin app. 我们正在使用静态类,并使它成为非静态类,并且该类负责在Xamarin应用中进行Web服务调用。 This is an object that I would definitely not want lying around. 我绝对不希望这是一个对象。 So I thought of having this class inherit the IDisposable interface, and I implemented the methods as shown: 因此,我想到让此类继承IDisposable接口,并实现了如下所示的方法:

private bool disposedValue = false; // To detect redundant calls

protected virtual void Dispose(bool disposing)
{
    if (!disposedValue)
    {
        if (disposing)
        {
            // TODO: dispose managed state (managed objects).
        }

        // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.
        // TODO: set large fields to null.

        disposedValue = true;
    }
}

// TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources.
//~WebServiceCallThread()
//{
//    // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
//    Dispose(false);
//}

// This code added to correctly implement the disposable pattern.
public void Dispose()
{
    // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
    Dispose(true);
    // TODO: uncomment the following line if the finalizer is overridden above.
    //GC.SuppressFinalize(this);
}

So all this appears to be doing, is when the Dispose method is called, it then calls a virtual method declared above Dispose(bool disposing) . 因此,所有这些似乎都在做,就是在调用Dispose方法时,它随后调用在Dispose(bool disposing)上方声明的虚拟方法。 With the current code, this does nothing (or so it seems). 对于当前的代码,这什么也没做(看起来如此)。 It just calls the Dispose method, in which that calls an overloaded Dispose method. 它只是调用Dispose方法,其中调用了重载的Dispose方法。 But nothing is actually "disposing" here. 但实际上,这里没有任何东西可以“处置”。

Upon some research, it SEEMS (which is why I'm asking, I think I am understanding correctly). 经过一些研究,它看起来很像(这就是为什么我要问的原因,我认为我理解正确)。 It says to only call a finalizer and the GC.SuppressFinalize method IF you dispose managed state . 它说,如果您dispose managed state ,则仅调用finalizerGC.SuppressFinalize方法。 I'm not sure what dispose manage state means, but there's really nothing in my class that needs to get disposed. 我不确定dispose manage state含义是什么,但是在我的课上确实没有什么需要配置的。 I just have some global int variables but that's it. 我只是有一些全局int变量,仅此而已。 The meat of this class is a HttpCall, which is already disposing of the objects automatically, as such: 此类的核心是HttpCall,它已经自动处理对象,例如:

public async void CallUrlHttpClient(string URL, System.Action<string> Handler, System.Action<XamarinMobile.Classes.ErrorInfo> ErrorHandler, int Tries)
        {
            var result = string.Empty;
            didMakeSuccessfulHttpRequest = false;

            using (var client = new HttpClient())
            {
               ... Code
            }
            ...

So here's my question: Do I need to make this class inherit IDisposable ? 所以这是我的问题:我是否需要使此类继承IDisposable I'm wondering if anything under the hood is being done, but it seems as if my application can just utilize the GC to get rid of my object that uses this class. 我想知道是否在做任何事情,但似乎我的应用程序可以利用GC摆脱使用此类的对象。 This is how I call it, via a static method in a class: 这就是我通过类中的静态方法调用它的方式:

    public static void WebServiceCall(string URL, System.Action<string> Callback)
    {
        //using (XamarinMobile.Classes.WebServiceCallThread thread = new Classes.WebServiceCallThread())
        //{
        XamarinMobile.Classes.WebServiceCallThread thread = new Classes.WebServiceCallThread();
        thread.Call(URL, Callback);
        //} 
    }

If I understand GC correctly, once this method is done, the GC will automatically get rid of the object. 如果我正确理解GC,则一旦完成此方法,GC就会自动摆脱该对象。 So do I really need to make the WebServiceCallThread inherit from IDisposable? 那么,我真的需要使WebServiceCallThread继承自IDisposable吗? Again I'm asking if I'm understanding all of this correctly. 我再次问我是否正确理解了所有这些。 If not, please correct me and let me know where I'm confused. 如果没有,请纠正我,让我知道我感到困惑的地方。

Thanks. 谢谢。

If your class created the HttpClient and maintained that instance throughout its own lifetime (like an instance variable) then you would implement IDisposable , and your Dispose() method would dispose the HttpClient . 如果您的类创建了HttpClient并在其整个生命周期中都维护了该实例(例如实例变量),则将实现IDisposable ,而Dispose()方法将处理HttpClient

That would be this part: 那就是这一部分:

if (disposing)
{
    // TODO: dispose managed state (managed objects).
    _httpClient.Dispose();
}

In this case you don't need to implement IDisposable because you're already disposing your HttpClient . 在这种情况下,您不需要实现IDisposable因为您已经在处理HttpClient

        using (var client = new HttpClient())
        {
           ... Code
        }

However, it's actually recommended to create one instance of HttpClient per endpoint and reuse it instead of creating and disposing over and over. 但是, 实际上建议每个端点创建一个HttpClient实例HttpClient用它,而不是一遍又一遍地创建和处理。 (If your load isn't that heavy then you likely won't see any bad effect from creating and disposing HttpClient .) (如果您的负载不是那么重,那么创建和处理HttpClient可能不会造成任何不良影响。)

If you wanted to avoid creating and disposing HttpClient then you could implement IDisposable . 如果要避免创建和处理HttpClient则可以实现IDisposable Your class either creates or receives (in its constructor) an instance of HttpClient . 您的类创建或接收HttpClient实例(在其构造函数中)。 Now that your class "owns" that instance which needs to be disposed when your class is disposed, you make your class IDisposable . 现在,您的类“拥有”了在处置您的类时需要处置的那个实例,您就可以使您的类IDisposable That way others know that your class needs to be disposed. 这样,其他人知道您的班级需要处置。 They might not know why, but that's not important. 他们可能不知道为什么,但这并不重要。 By making it IDisposable you're letting them know that they need to dispose it. 通过使其成为IDisposable您可以让他们知道他们需要处理它。 And then when your class is disposed it cleans up its HttpClient . 然后,当您的类被处置时,它将清理其HttpClient


Just to provide a little extra clarification: 只是提供一些额外的说明:

Many people, if asked "What is IDisposable for?" 许多人被问到“ IDisposable用途是什么?” will answer that it causes garbage collection. 会回答这会导致垃圾收集。 It actually has nothing to do with garbage collection. 实际上,它与垃圾回收无关。 Objects always get garbage collected when they're out of scope (there are no more references to them) whether or not they implement IDisposable . 无论对象是否实现IDisposable ,它们总是在超出范围时(不再有对其的引用)被垃圾回收。

The confusion comes up because the recommended pattern for IDisposable (which you referenced) includes a finalizer ( ~WebServiceCallThread() ) which is called when the object is garbage collected. 之所以会出现混乱,是因为IDisposable的推荐模式(您所引用的模式)包括一个终结器( ~WebServiceCallThread() ),该终结器在对象被垃圾回收时被调用。

When the garbage collector removes an item it calls the finalizer if there is one. 当垃圾收集器删除一项时,如果有一项,它将调用终结器。 This pattern causes the finalizer to call Dispose() if it hasn't been called already, just as a backup in case someone didn't call Dispose() like they were supposed to. 如果尚未调用终结器,则此模式将使终结器调用Dispose() ,以防万一有人不按预期调用Dispose()情况下进行备份。 But it's no substitute for calling Dispose() because there's no telling when the garbage collector will collect the item. 但这不能替代调用Dispose()因为没有告诉垃圾收集器何时收集该项目。 There's a chance the finalizer will never get called. 终结者有可能永远不会被调用。 It's just a backup to try to mitigate what happens if consumers don't call Dispose() . 它只是试图减轻如果消费者不调用Dispose()会发生的情况的备份。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我是否需要在实现IDisposable的每个对象中使用“using”关键字? - Do I need to use “using” keyword in every object which implements IDisposable? 为什么我需要在子类上实现 IDisposable() - Why do I need I need to implement IDisposable() on a child class 当我将它传递给IDisposable类时,我需要Dispose Stream吗? - Do i need to Dispose Stream when i Pass it to IDisposable class? 如果我的类实现了 IDisposable,为什么我需要终结器? - Why do I need a finalizer if my class implements IDisposable? 我是否需要处置与应用程序本身具有相同生存期的IDisposable? - Do I need to dispose IDisposable that have the same lifetime as the application itself? 如何为IDisposable类型使用自定义生成器? - How do I use a custom generator for IDisposable types? 使用 IDisposable 取消订阅事件——我是否需要在 dispose 中放入其他东西? - Using IDisposable to unsubscribe an event— do I need to put other things inside the dispose? 使用C#的“ using”语句和自定义对象的函数时,是否需要实现IDisposable? - Using C#'s 'using' statement with a custom object's function, do I Need to implement IDisposable? 在处理类实例时,是否需要显式处理其所有 IDisposable 成员? - While disposing the class instance, do i need to dispose all its IDisposable members explicitly? 我真的需要基本处理模式来引用其他 IDisposable 对象的类型吗? - Do I really need Basic dispose pattern for type referencing other IDisposable objects?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM