I have an IDisposable class A. I need to use an object of A inside another method M of class B. Method M is called multiple times (million times a day). Should I use local object of A inside M and dispose once done or should I declare class level static member inside B and dispose once application ends. Let me know if I am not clear.
Asked
Active
Viewed 297 times
1
-
Why can't B take an A instance in its constructor and supply it to M as needed, and then B can destroy it when it's done with it? An object is responsible for cleanup of resources it provides via public interface unless that interface is a factory method or a constructor, in which case the caller is responsible. – hoodaticus Feb 20 '17 at 19:17
-
Each call to M is through new instance of B. – Nisha Kant Feb 20 '17 at 19:55
-
1Sounds like singleton is appropriate here, assuming it's thread safe. – hoodaticus Feb 20 '17 at 19:55
1 Answers
1
One object for the life of the application is a Singleton; while they are useful under specific circumstance, they are not generally a good idea. See this question for a detailed explanation of why.
Classes that implement IDisposable
are best used within the confines of a using
statement that will take care of disposing it for you.
The clear exception to this is when multiple calls to the disposable class will be needed in the context of a single business action -- and that action is too spread out to be wrapped in a using
statement. In this case, wrapping all the calls into a second disposable class that has the first as a private member. when the second class is disposed it should dispose of any private members that are disposable.

Community
- 1
- 1

David Culp
- 5,354
- 3
- 24
- 32
-
Calls to method M of class B originating from multiple instances of B. Like below B b = new B() b.M() I don;t see a point of making B disposable. – Nisha Kant Feb 20 '17 at 19:51
-
Another non-obvious case where a class that implements `IDisposable` should be held for the life of the application, and not used inside a `using` is `HttpClient`. More information can be found [here](https://aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/). – Bradley Uffner Feb 20 '17 at 20:06
-
@BradleyUffner that was the most prominent example on my mind that kept me from speaking in absolutes. – David Culp Feb 20 '17 at 20:11