When a derived class overrides Dispose should the base class Dipose be called first before the derived class disposes of any local resources?
The reason I ask is because someone on our team is saying yes for every scenario, I'm trying to work out if this is good idea or just 'cargo cult' programming, I don't have a strong view either way.
Before:
public override void Dispose()
{
base.Dispose();
if (!_isDisposed)
{
_isDisposed = true;
if (_foo != null)
{
_foo.Dispose();
}
}
}
After:
public override void Dispose()
{
if (!_isDisposed)
{
_isDisposed = true;
if (_foo != null)
{
_foo.Dispose();
}
}
base.Dispose();
}
Note: I'm not looking for how to implement the basic dispose pattern but more clarification from peoples experiences.
"It depends"
You can't have a hard-and-fast rule for this, because the order you need to call dispose will depend on the implementation of the classes.
Sometimes you might want it at the start, sometimes at the end, and sometimes in the middle. Most of the time, it probably won't matter.
Generally speaking, people seem to call it first (in the absence of any other reason to call it at a different time).
One reason to lean towards calling it first is that then the derived class has a chance to do special stuff afterwards if it needs to.
You should think about the consequences of the different approaches. In most cases, the IDisposable objects owned by the base class will be independent of those owned by the derived class, and the order of disposal won't matter, provided none of the Dispose methods throws an Exception (*).
If it's critical to release an IDisposable resource, you could consider using try/finally to ensure all Dispose methods are called - but this isn't universally done. For example, the System.Component.Container class manages and disposes multiple IDisposable objects, but makes no attempt to ensure they are all disposed if an exception is thrown.
(*) It's perfectly legitimate for Dispose to throw: for example a FileStream might attempt to flush data to a network resource that's no longer available during Dispose.
Dispose object in the reverse order to create. So firstly is created base class, so it should be dispose in the end, and so on...
Related
A question for you all.
In my company, we are developing an application that runs inside Microsoft’s MVC framework.
The controller classes that we are implementing inherit from the MVC base class Controller. Example:
public class MyController: Controller
{
protected bool IsDisposed { get; set; }
… various methods…
}
The discussion we are having in the team centers around the Dispose() pattern. Essentially, this involves implementing the IDisposable interface, preferably according to the Microsoft-endorsed pattern.
See for example this link: http://msdn.microsoft.com/en-us/library/fs2xkftw%28v=vs.110%29.aspx
Interestingly, our controller classes do not own any resources, either managed or managed. As a result, the implementation of Dispose(bool) is greatly simplified:
protected override void Dispose(bool disposing)
{
IsDisposed = true;
base.Dispose(disposing);
}
There is some disagreement about the use (or need) of the IsDisposed property, that is used in the following method:
protected void ThrowIfDisposed()
{
if (IsDisposed) throw new ObjectDisposedException(“MyController”);
}
This method is then called at the beginning of every method that does "real" work. The thinking here is that a disposed object should not be used again, hence it should throw the ObjectDisposedException. The other opinion is that, since Dispose(bool) does “nothing” (other than setting the IsDisposed property and calling Dispose(bool) on the base class), the “disposed” object is not really in a state that is unusable, so there is no reason to throw. Therefore, there is no reason to even implement Dispose(bool).
An argument against this is that MyController should throw when it is disposed and one of its methods is called, so that its behaviour does not change should in future versions managed and/or unmanaged resources be added.
The argument against this last point is that MyController should never add any resources in future versions, but rather it should be derived from should the need to add resources occur in the future. An additional question is: why doesn’t the (library) class Controller implement ThrowIfDisposed() or something similar?
So, summarizing, faction one wants to implement Dispose(bool) and ThrowIfDisposed() as shown above, faction two thinks they are unnecessary and wants to do away with them.
I see merits in both viewpoints, cannot really make up my mind. Opinions?
Interestingly, our controller classes do not own any resources, either managed or managed.
Then you do not need the IDisposable pattern.
This method [ ThrowIfDisposed() ] is then called at the beginning of every method that does “real” work.
The qustion here is: Why?
If you do want to track a usable/abandoned state then just don't call it IsDisposed.
why doesn’t the (library) class Controller implement ThrowIfDisposed() or something similar?
Because it isn't useful.
Go back to the beginning: why did somebody think this was necessary? What is it for?
It seems you can just rip it out.
If an object receives a request after being disposed, the request should not fail for any reason other than ObjectDisposedException--meaning it shouldn't cause a NullReferenceException, yield garbage data, crash the system, or do any other such thing. That does not imply that the request shouldn't succeed--merely that ObjectDisposedException should be the only mode of failure.
As for IsDisposed, I can't really see much use for it in most cases. Code which doesn't know whether an object is disposed generally won't know much else enough about the object's state to know whether it might be unusable for some other reason; consequently, code that doesn't know whether an object is disposed generally shouldn't do anything with it except--in some cases--to Dispose it, and in most of those cases where one would want to call Dispose on an object if it hadn't already been disposed, one should simply call Dispose unconditionally. There could be some value in having a method MayNeedDisposing which would return true for objects with non-trivial Dispose methods until they've been disposed, but such a method could unconditionally return false for objects with null Dispose methods [in cases where a class would e.g. register a callback purely for the purpose of calling Dispose on something, testing MayNeedDisposing beforehand could be a useful optimization].
Finally, with regard to whether a class or interface should implement or inherit IDisposable, the issue is not whether the type itself acquire resources, but rather whether the last surviving reference to something that does acquire resources may be stored in that type. For example, even though the vast majority of IEnumerator<T> implementations don't acquire resources, some do, and in many such cases the only references to such objects will be stored in variables of type IEnumerator<T>, held by code that has no idea whether the objects in question have any resources or not. Note that non-generic IEnumerator doesn't implement IDisposable but some implementations acquire resources. As a consequence, code which calls IEnumerable.GetEnumerator will be required to call Dispose on the returned enumerator if it implements IDisposable. The fact that IEnumerator doesn't inherit IDisposable doesn't absolve code which receives an IEnumerator implementation that also implements IDisposable from the responsibility of calling Dispose--it merely makes it harder for such code to carry out that responsibility.
Faction two is absolutely right. Don't do it.
Implementing IDisposable in the way described and for the reasons given is a violation of at least three good principles.
You ain't gonna need it. http://c2.com/cgi/wiki?YouArentGonnaNeedIt
Do the simplest thing that could possibly work. http://www.xprogramming.com/Practices/PracSimplest.html
Keep it simple stupid. https://en.wikipedia.org/wiki/KISS_principle
It's just wrong on every level. Don't do it.
In C#, if a class, such as a manager class, does not have resources, is there any benefit to having it : IDisposable?
Simple example:
public interface IBoxManager
{
int addBox(Box b);
}
public class BoxManager : IBoxManager
{
public int addBox(Box b)
{
using(dataContext db = new dataContext()){
db.Boxes.add(b);
db.SaveChanges();
}
return b.id;
}
}
Will there be any benefit in memory use when using BoxManager if it also implements IDisposable? public class BoxManager : IBoxManager , IDisposable
For example:
BoxManager bm = new BoxManager();
bm.add(myBox);
bm.dispose();//is there benefit to doing this?
There are only 2 reasons for implementing IDisposable on a type
The type contains native resources which must be freed when the type is no longer used
The type contains fields of type IDisposable
If neither of these are true then don't implement IDisposable
EDIT
Several people have mentioned that IDisposable is a nice way to implement begin / end or bookended operations. While that's not the original intent of IDisposable it does provide for a very nice pattern.
class Operation {
class Helper : IDisposable {
internal Operation Operation;
public void Dispose() {
Operation.EndOperation();
}
}
public IDisposable BeginOperation() {
...
return new Helper() { Operation = this };
}
private void EndOperation() {
...
}
}
Note: Another interesting way to implement this pattern is with lambdas. Instead of giving an IDisposable back to the user and hoping they don't forget to call Dispose have them give you a lambda in which they can execute the operation and you close out the operation
public void BeginOperation(Action action) {
BeginOperationCore();
try {
action();
} finally {
EndOperation();
}
}
There won't be a scrap of difference between the disposable and non-disposable version if you don't explicitly make use of the Dispose() method.
While your code wouldn't benefit from implementing IDisposable, I can't agree with other opinions here that state that IDisposable is only meant to (directly or indirectly) free native resources. IDisposable can be used whenever the object needs to perform clean up task at the end of it's lifetime span. It's extremely useful together with using.
A very popular example: in ASP.NET MVC Html.BeginForm returns an IDisposable. On creation, the object opens the tag, when Dispose is called it closes it. No native resources involved, yet still a good use of IDisposable.
No, there will be no benefit if you don't do something useful like releasing unmanaged resources that your class might hold in the Dispose method.
One major point of confusion, which may not be applicable in your case but arises often, is what exactly constitutes a "resource". From the perspective of an object, an unmanaged resource is something which an outside entity () is "doing"(*) on its behalf, which that outside entity will keep doing--to the detriment of other entitites--until told to stop. For example, if an object opens a file, the machine which hosts the file may grant that object exclusive access, denying everyone else in the universe a chance to use it unless or until it gets notified that the exclusive access isn't needed anymore.
(*) which could be anything, anywhere; possibly not even on the same computer.
(**) or some way in which the the behavior or state of an outside entity is altered
If an outside entity is doing something on behalf of an object which is abandoned and disappears without first letting the entity know its services are no longer required, the outside entity will have no way of knowing that it should stop acting on behalf of the object which no longer exists. IDisposable provides one way of avoiding this problem by providing a standard means of notifying objects when their services are not required. An object whose services are no longer required will generally not need to ask any further favors from any other entities, and will thus be able to request that any entities that had been acting on its behalf should stop doing so.
To allow for the case where an object gets abandoned without IDisposable.Dispose() having been called first, the system allows objects to register a "failsafe" cleanup method called Finalize(). Because for whatever reason, the creators of C# don't like the term Finalize(), the language requires the use of a construct called a "destructor" which does much the same thing. Note that in general, Finalize() will mask rather than solve problems, and can create problems of its own, so it should be used with extreme caution if at all.
A "managed resource" is typically a name given to an object which implements IDisposable and usually, though not always, implements a finalizer.
No, if there are no (managed or unmanaged) resources there is no need for IDisposable either.
Small caveat: some people use IDisposable to clean up eventhandlers or large memory buffers but
you don't seem to use those
it's a questionable pattern anyway.
From my personal experience (confirmed with discussion and other posts here) I would say, that there could be a situations where your object use massive amount of events, or not massive amount but frequent subscriptions and unsubscription from the event which sometimes leads to that the object is not garbage collected. In this case I in Dispose unsubscribe from all events my object subscribed before.
Hope this helps.
IDisposable is also great if you want to benefit the using () {} syntax.
In a WPF project with ViewModels, I wanted to be able to temporarily disable NotifyPropertyChange events from raising. To be sure other developers will re-enable notifications, I wrote a bit of code to be able to write something like:
using (this.PreventNotifyPropertyChanges()) {
// in this block NotifyPropertyChanged won't be called when changing a property value
}
The syntax looks okay and is easily readable. For it to work, there's a bit of code to write. You will need a simple Disposable object and counter.
public class MyViewModel {
private volatile int notifyPropertylocks = 0; // number of locks
protected void NotifyPropertyChanged(string propertyName) {
if (this.notifyPropertylocks == 0) { // check the counter
this.NotifyPropertyChanged(...);
}
}
protected IDisposable PreventNotifyPropertyChanges() {
return new PropertyChangeLock(this);
}
public class PropertyChangeLock : IDisposable {
MyViewModel vm;
// creating this object will increment the lock counter
public PropertyChangeLock(MyViewModel vm) {
this.vm = vm;
this.vm.notifyPropertylocks += 1;
}
// disposing this object will decrement the lock counter
public void Dispose() {
if (this.vm != null) {
this.vm.notifyPropertylocks -= 1;
this.vm = null;
}
}
}
}
There are no resources to dispose here. I wanted a clean code with a kind of try/finally syntax. The using keyword looks better.
is there any benefit to having it : IDisposable?
It doesn't look so in your specific example, however: there is one good reason to implement IDisposable even if you don’t have any IDisposable fields: your descendants might.
This is one of the big architectural problems of IDisposable highlighted in IDisposable: What your mother never told you about resource deallocation. Basically, unless your class is sealed you need to decide whether your descendants are likely to have IDisposable members. And this isn't something you can realistically predict.
So, if your descendants are likely to have IDisposable members, that might be a good reason to implement IDisposable in the base class.
Short answer would be no. However, you can smartly use the nature of the Dispose() executement at the end of the object lifecycle. One have already gave a nice MVC example (Html.BeginForm)
I would like to point out one important aspect of IDisposable and using() {} statement. At the end of the Using statement Dispose() method is automatically called on the using context object (it must have implemented IDisposable interface, of course).
There one more reason that no one mentioned (though it's debateful if it really worth it):
The convension says that if someone uses a class that implement IDisposable, it must call its Dispose method (either explicitly or via the 'using' statement).
But what happens if V1 of a class (in your public API) didn't need IDisposable, but V2 does? Technically it doesn't break backward compatibility to add an interface to a class, but because of that convension, it is! Because old clients of your code won't call its Dispose method and may cause resources to not get freed.
The (almost) only way to avoid it is to implement IDisposable in any case you suspect that you'll need it in the future, to make sure that your clients always call your Dispose method, that some day may be really needed.
The other (and probably better) way is to implemet the lambda pattern mentioned by JaredPar above in the V2 of the API.
While crawling through sources on the web, I've encountered a lot of boiletplate code which looks the following way:
Suppose we have some public class CustomObject: IDisposable, which has a bunch of methods.
Now, each of those methods has default sanity checks:
if (inputBuffer == null)
throw new ArgumentNullException("inputBuffer");
if (outputBuffer == null)
throw new ArgumentNullException("outputBuffer");
if (inputCount < 0)
throw new ArgumentException("inputCount", "< 0");
But (due to the IDisposable interface implementation) the following check is added to each method:
if (disposed)
throw new ObjectDisposedException("MethodName");
Now - is this a common practice? Should I start reengineering my old disposable classes and implementing these checks?
Now - is this a common practice?
Yes, it is recommended. For almost all members. If you class is IDisposable and any method that needs a resource is called after Dispose() then there is a serious logic error in the calling code. Your task is to signal this.
But note that there might be methods (or properties) that do not critically rely on the owned resource(s), they can be considered safe to call after a Dispose(). For instance an IsOpen function/property. It can simply return false, no need for an exception.
But you should not put the IsDisposed check into Dispose() iteself, the guideline is that it should be safe to call Dispose() multiple times.
Should I start reengineering my old disposable classes and implementing these checks?
In general a good idea. Whether it is worth the effort is up to you.
It depends upon your usage, if in doubt it doesn't hurt to add it.
For a class intended to be used by other programs (e.g., libraries and frameworks) I would always perform this check and throw the correct exception as this will aid other applications in diagnosing errors and makes the class more robust.
For internal classes only intended to be consumed by my application you can skip the check if the error will surface quickly when calling the methods. E.g. if every method in the class used a stream, and that stream was disposed or set to null it would result in an exception pretty quickly.
If the internal class has methods that won't error though, I will always use an explicit check as I don't want a situation where some of the methods still work after the object has been disposed (except for methods that explicitly allow it such as IsDisposed).
Having the explicit check does have the advantage of explicitly documenting which methods are allowed to be called after the object has been disposed. More so if you add a comment at the top of methods that do not call GuardDisposed to state that it is allowed, then any method that doesn't start with GuardDisposed or a comment can be regarded as suspect.
To actually implement the check I prefer to move it to a separate method and use it like an assertion, e.g.
public class Foo
{
private bool disposed;
public void DoSomething ()
{
GuardDisposed ();
}
protected void GuardDisposed ()
{
if (disposed)
throw new ObjectDisposedException (GetType ().Name);
}
}
That code you put inside Dispose() (usually) method in order to be sure that it's not called esplicitly (and/or) not esplicitly more then one time on a single instance.
They use it in case when you do in that method something that can be executed one time (DeleteFile, CloseTransaction...) and any other operation you may think of, that is shouldn't executed twice in your app domain.
So if this is a common practice: I would say, it depends on your app requirements.
Say I have the following:
public abstract class ControlLimitBase : IDisposable
{
}
public abstract class UpperAlarmLimit : ControlLimitBase
{
}
public class CdsUpperAlarmLimit : UpperAlarmLimit
{
}
Two Questions:
1.
I'm a little confused on when my IDisposable members would actually get called. Would they get called when an instance of CdsUpperAlarmLimit goes out of scope?
2.
How would I handle disposing of objects created in the CdsUpperAlarmLimit class? Should this also derive from IDisposable?
Dispose() is never called automatically - it depends on how the code is actually used.
1.) Dispose() is called when you specifically call Dispose():
myAlarm.Dispose();
2.) Dispose() is called at the end of a using block using an instance of your type.
using(var myAlarm = new CdsUpperAlarmLimit())
{
}
The using block is syntactic sugar for a try/finally block with a call to Dispose() on the object "being used" in the finally block.
No, IDisposable won't be called just automatically. You'd normally call Dispose with a using statement, like this:
using (ControlLimitBase limit = new UpperAlarmLimit())
{
// Code using the limit
}
This is effectively a try/finally block, so Dispose will be called however you leave the block.
CdsUpperAlarmLimit already implements IDisposable indirectly. If you follow the normal pattern for implementing IDisposable in non-sealed classes, you'll override void Dispose(bool disposing) and dispose your composed resources there.
Note that the garbage collector does not call Dispose itself - although it can call a finalizer. You should rarely use a finalizer unless you have a direct handle on unmanaged resources though.
To be honest, I usually find it's worth trying to change the design to avoid needing to keep hold of unmanaged resources in classes - implementing IDisposable properly in the general case is frankly a pain. It's not so bad if your class is sealed (no need for the extra method; just implement the Dispose() method) - but it still means your clients need to be aware of it, so that they can use an appropriate using statement.
IDisposable has one member, Dispose().
This is called when you choose to call it. Most typically that's done for you by the framework with the using block syntactic sugar.
I'm a little confused on when my IDisposable members would actually get called. Would they get called when an instance of CdsUpperAlarmLimit goes out of scope?
No. Its get called when you use using construct as:
using(var inst = new CdsUpperAlarmLimit())
{
//...
}//<-------- here inst.Dispose() gets called.
But it doesn't get called if you write this:
{
var inst = new CdsUpperAlarmLimit();
//...
}//<-------- here inst.Dispose() does NOT get called.
However, you can write this as well:
var inst = new CdsUpperAlarmLimit();
using( inst )
{
//...
}//<-------- here inst.Dispose() gets called.
The best practice recommend when you implement Dispose() method in non sealed class you should have a virtual method for your derived classes to override.
Read more on Dispose pattern here http://www.codeproject.com/KB/cs/idisposable.aspx
when using an IDisposable object, it's always good to use it this way:
using(var disposable = new DisposableObject())
{
// do you stuff with disposable
}
After the using block has been run, the Dispose method will be called on the IDisposable object. Otherwise you would need to call Dispose manually.
When someone calls .Dispose on it.
No, it already implements it through inheritance.
IDisposable is implemented when you want to indicate that your resource has dependencies that must be explicitly unloaded and cleaned up. As such, IDisposable is never called automatically (like with Garbage Collection).
Generally, to handle IDisposables, you should wrap their usage in a using block
using(var x = new CdsUpperAlarmLimit()) { ... }
this compiles to:
CdsUpperAlarmLimit x = null;
try
{
x = new CdsUpperAlarmLimit();
...
}
finally
{
x.Dispose();
}
So, back to topic, if your type, CdsUpperAlarmLimit, is implementing IDisposable, it's saying to the world: "I have stuff that must be disposed". Common reasons for this would be:
CdsUpperAlarmLimit keeps some OTHER IDisposable resources (like FileStreams, ObjectContexts, Timers, etc.) and when CdsUpperAlarmLimit is done being used, it needs to make sure the FileStreams, ObjectContexts, Timers, etc. also get Dispose called.
CdsUpperAlarmLimit is using unmanaged resources or memory and must clean up when it's done or there will be a memory leak
I have a NHibernate repository that looks like this:
public class NHibRepository : IDisposable
{
public ISession Session { get; set; }
public ITransaction Transaction { get; set; }
// constructor
public NHibRepository()
{
Session = Database.OpenSession();
}
public IQueryable<T> GetAll<T>()
{
Transaction = Session.BeginTransaction();
return Session.Query<T>();
}
public void Dispose()
{
if (Transaction != null && Transaction.IsActive)
{
Transaction.Rollback(); // ObjectDisposedException on this line
}
Session.Close();
Session.Dispose();
}
~NHibRepository()
{
Dispose();
}
}
When I use the repository like this, it runs fine:
using (var repo = new NHibRepository())
{
Console.WriteLine(repo.GetAll<Product>().Count());
}
But when I use it like this, it will throw an ObjectDisposedException:
var repo = new NHibRepository();
Console.WriteLine(repo.GetAll<Product>().Count());
The easy solution would be to always dipose of the repository explicitly, but unfortunately I don't control the life cycle of some of the classes that use the repository.
My question is, why is the Transaction disposed of already even though I did not explicitly call Dispose()? I'd like to have the repository automatically clean itself up if it was not disposed explicitly.
My question is, why is the Transaction disposed of already even though I did not explicitly call Dispose()?
Perhaps the transaction's finalizer ran first. Remember, finalizers of dead objects can run in any order and on any thread, and need not have been correctly initialized before they are finalized. If you do not understand all the rules of finalizers then learn them all before you attempt to write any more code that uses finalizers. This is one of the hardest things to get right.
It also looks as though you have implemented the disposable pattern incorrectly, and that is going to cause you a world of grief. Read up on the pattern and do it correctly; the finalizer should not be disposing stuff that has already been disposed:
http://msdn.microsoft.com/en-us/magazine/cc163392.aspx
Lose the finalizer. Very few classes in .net need a finalizer; generally, the only .net 2.0-or-later classes which should have finalizers are those whose sole reason for existence revolves around it.
If a class with a finalizer holds an access to some other object, one of three conditions will apply when the finalizer is run:
The other object has already had its finalizer (if any) run; there's no need to dispose it, since it's already been taken care of.
The other object has a finalizer scheduled to run; there's no need to dispose it, since it will be taken care of automatically.
A reference to the other object exists outside of the object whose finalizer is running; this usually means one shouldn't dispose it.
The only time a finalizer should ever take any action to dispose of a manage object is when an outside reference is likely to exist, and the collection of the object being finalized will imply that the other object should be disposed despite the existence of that reference. That's a very rare situation.
You should put GC.SuppressFinalize(this); in your Dispose method otherwise the finalizer will dispose an already disposed object. Also, finalizers are in almost all cases only needed for unmanaged resources
The CLR makes no guarantees with respect to the order that finalizers will be called. It sees a group of unrooted objects (e.g. not reachable from any GC root) and starts calling finalizers. It doesn't matter that you have connections within your object graph. The finalizers can be called in any order. Finalizers are intended to clean up unmanaged resources, not child objects. You need to re-think your API.
You should have a member variable isDisposed that would be set to true by the Dispose() method. Then at the beginning of the Dispose() command just return if it is already set to true. According to .NET whitepapers, Dispose() could be executed multiple times without side effects and this is the way to do it.
Secondly, make the class sealed (the class is not implementing the Dispose pattern properly for inheritance) and put GC.SuppressFinalize(this); right before the isDisposed variable assignment in the Dispose() method.
public void Dispose()
{
if (isDisposed) { return; }
....
GC.SuppressFinalize(this);
isDisposed = true;
}