Behavior of disposed object - c#

I have a class with IDisposable interface. Now I don't know what behavior should I implement. Should be thrown an ObjectDisposedException for each method call in this class after Dispose method, or it should only throw exception in specified methods like data access to disposed resources?
I tested Bitmap object (just example):
Bitmap b = new Bitmap (100, 100);
b.Dispose (); // if i remove this line - console will display: Format32bppArgb
Console.WriteLine (b.PixelFormat);
Console.ReadKey ();
And console displays: DontCare
So no exception has been thrown. Bitmap object allow to use PixelFormat property after I called Dispose. Should I follow this behavior?

My philosophy on this and many other issues is "do what makes sense".
In some cases, it may be very reasonable for certain class members to be used after a class has released its resources. Indeed, some scenarios may require such use. For example, if an object manages asynchronous transactions over a network connection, one might ask it to shut down and then, after it has done so, ask it how many transactions had been processed, whether any had been left dangling, etc. The final values of such statistics could not be known until after shutdown is complete, and there is conceptually nothing wrong with asking an object to shut down and then asking it for historical information relating to things it has already done.
While one might argue that Close should shut down the connection while allowing the use of properties that report historical informaion, while Dispose should shut things down and disallow the use of such properties, I regard such a distinction as unhelpful. Among other things, one may wish for the connection to release all resources associated with it (something Close might refrain from doing, in the interest of allowing a "reopen" request). Further, in cases where there's no other difference in behavior between Close and Dispose, I don't see any need to require two separate methods purely so Dispose can invalidate the statistical data.
In some sense, many IDisposable objects may be viewed as having two parts--an entity which is interacts with outside resources, and an entity which interacts with managed code and may have limited functionality by itself. While the "separation of concerns" principle would suggest that the two parts should be separate objects (and indeed, there are tines when such a split can be helpful), in many cases client code is going to want to hold a single reference which can serve both purposes. That reference is going to have to implement IDisposable, but disposal shouldn't destroy the managed-code side of things.
As an example, consider the WinForms Font class. That class encapsulates two things: (1) a collection of information about a font (typeface, size, style, etc.), and (2) a GDI font handle. When a Font is Disposed, it can no longer be used for drawing text, but it does not forget the typeface, style, etc. Given a Disposed font, it is possible to construct a new font using that information from an old one. Unfortunately, most of the properties that would allow such information to be read out are explicitly invalidated by Dispose, which means that in many cases if one wants to produce a font which is similar to an existing-but-disposed Font but has some changes, one must construct a new font with information copied from the old one, construct another new font based upon that one, and then Dispose the first new font that was created. It might have been helpful to have a FontDescription class which held information related to typestyle, etc. so that in cases where one wanted to hold a description of a font but didn't need a GDI handle, the font description could be stored in a non-disposable class, but that's not how the classes were designed.

should only throw exception in specified methods like data access to disposed resources?
That's automatic, a class that has a finalizer should throw in a case like this. After all, the method is going to access an operating system object that's no longer alive, that is going to produce an error. That better be reported with a clear one like ObjectDisposedException instead of a mystifying one produced by the operating system error code.
The Bitmap example you gave is a very sad one, but not uncommon for the GDI+ classes. They in general have very poor error handling. Let this not be an example.
The key phrase in the previous paragraph was "class that has a finalizer". Your class should not have a finalizer so whether you throw yourself instead of leaving it up to the method in the disposable class you encapsulate is debatable. In general you should avoid it, it tends to clutter your code for little real benefit. But feel free to do so if you wrap a crummy class like Bitmap that returns bad data.

After calling dispose, setting the object to null is the approach I generally follow. Then, you do not need to create any exception, since null exception will be thrown, and it seems to be the proper way.
When an object is null, it does not really matter whether it is null since it is disposed; or it is null as it is not initialized or it is null as it is explicitly set to null. The consumers should know it is null, not the underlying action of being null.

Related

What are the rules for when dispose() is required?

Although I have been coding for some time, I'm really just barely into what I would call an intermediate level coder. So I understand the principle of dispose(), which is to release memory reserved for variables and/or resources. I have also found sometimes using EF I have to dispose() in order for other operations to work properly. What I don't understand is just exactly what requires a release, when to employ dispose().
For example, we don't dispose variables like string, integer or booleans. But somewhere we cross 'a line' and the variables and/or resources we use need to be disposed. I don't understand where the line is.
Is there a single principle or a few broad principles to apply when knowing when to use dispose()?
I read these SO posts (a specific situation, more about how rather than when ) but I don't feel like I understand the basics of knowing when to use dispose(). One comment I saw asked if memory is released when a variable goes out of scope, and that got my attention because until I saw the response was no, it doesn't get released just because it goes out of scope, I would have thought that it does get released when it goes out of scope. I don't want to be what one person in the 2nd link called a 'clueless developer', although I thought that was a little harsh. Some of us are still learning.
So that's why my question is "What determines when a dispose() is really necessary?"
My question is less one of how and more one of when. Of course comments on how would be useful, but even if the method for invoking dispose() is a Using statement, I still need to know when.
Edit to original question: I know this is a long explanation as the marked as duplicate comment note requests, and it's not a rant, I just don't know how to make sure I get the focus on my precise question. Often times we just trip up over the way we ask something. As I mention at the end of this long text I'll edit all this out after we've gotten focused on my issue, assuming we get there. Based on what I've read, I think it's an important question.
The proposed "answer" post is a great post, but doesn't really answer my question. CodeNotFound's comment below also gives a great link but it doesn't really answer my question either. I've provided comments regarding these posts to try and help refine my precise question:
When should I dispose my objects in .NET?: The first answer starts with a comment that
Disposable objects represent objects holding a valuable resource which the CLR is not intrinsically aware of.
Unfortunately I don't understand what the term "Disposable objects ... the CLR is not intrinsically aware of" includes. That's what I'm asking. How do I know if something falls into the category of what I must dispose? We define things to use in code all the time. When do we cross the line and it becomes an object I need to dispose()? BTW, I noticed the author of that post never marked an answer. I don't know if that means he didn't feel the question was answered or if it was just poor follow up on his part, but hopefully I've refined a little what I hoping to understand. When you look closely at the answers, they're not really addressing the issue of which objects require a developer's action to dispose() of them, or how I might go about knowing how to identify which objects. I just don't know what objects or things I create require that I am responsible for disposing. And I get it that GC and other provisions come into play, but again, that's just the how. What seems clear is that most experienced and professional developers know when something they've created needs to be disposed of. I don't understand how to know that.
Proper use of the IDisposable interface: Clearly a popular answer (1681 upvotes), but the marked answer begins with
The point of Dispose is to free unmanaged resources".
OK, but my question is how do I know by looking at something that it is an unmanaged resource? And I don't understand how the note that follows applies to what needs to be disposed.
If you found it in the .NET framework it's managed. If you went poking around MSDN yourself, it's unmanaged... and you're now responsible for cleaning it up."
I don't understand how to use that type of explanation to categorize what I need to dispose() and what I don't. There's all kinds of stuff in the .net framework; how do I separate out things that require I dispose() of them? What do I look at to tell me I'm responsible for it?
After that, the answer goes on to speak at great length about how to dispose(), but I'm still stuck back at what needs to be disposed. To further complicate the topic for me, that author later says "So now we will...
get rid of unmanaged resources (because we have to), and
get rid of managed resources (because we want to be helpful)
So now I need to consider disposing a whole new set of objects that use memory, and I don't know what those are either. The author of the answer later says
For anyone who likes the style of this answer (explaining the why, so the how becomes obvious)...
I understand the author was suggesting other articles, but the author's suggestion that understanding the "why" makes the "how" obvious isn't really legitimate because what's obvious to one person isn't always obvious to another. And even at that, the author focused more on the why and how, and my question is about when, meaning what needs to be disposed(), as opposed to when I'm done with it. I know when I'm done with things, I just don't know which things I'm responsible for when I'm done with them.
It may be obvious or instinctive to most developers what needs to be disposed(), but it's not obvious to me and I'm sure many others at my stage of experience and I was hoping to get a more focused dialogue on what. Certainly why is useful, but in this case only if the why is attached to a what. For example: You have to dispose a DbContext because the CLR won't dispose it - the because explains why, but in this case, it's the DbContext that is the what that must be disposed.
I was hoping there is a general principle for what must be disposed rather than a long list of specific items which would not be particularly useful for people like me who are looking for simple guidelines.
Again, I get it that memory release is important, and also that a lot of experience and expertise goes into learning why and how, but I'm still left struggling to understand what needs to be disposed. Once I understand what I have to dispose(), then I can begin the struggle to learn how to do it.
So is this still a bad question? I'll edit out all of this explanation later to leave the post more succinct assuming we're able to achieve more focus on what I'm asking.
Final Edit: Although I said above I would edit out what I originally thought to be unnecessary text in the question, I think it better to leave it in. I think the way questions are asked has the potential to help us understand the answer. Even though the answer never changes, if we don't connect the answer to the way we framed the question in our minds, we may not really understand the answer. So if the way this question was framed connects with someone, I encourage you to fully read the post marked as the answer, along with the comments. While the answer in the end was really simple, there's a great deal of history and also context that is important to understand the answer to this question. For clarity's sake, the answer was also edited back and forth over the life of this discussion regarding dispose(). Enjoy...
I understand the principle of dispose(), which is to release memory reserved for variables and/or resources.
You do not understand the purpose of dispose. It is not for releasing memory associated with variables.
What I don't understand is just exactly what requires a release, when to employ dispose().
Dispose anything that implements IDisposable when you are sure that you are done with it.
For example, we don't dispose variables like string, integer or booleans. But somewhere we cross 'a line' and the variables and/or resources we use need to be disposed. I don't understand where the line is.
The line is demarcated for you. When an object implements IDisposable, it should be disposed.
I note that variables are not things that are disposed at all. Objects are disposed. Objects are not variables and variables are not objects. Variables are storage locations for values.
Is there a single principle or a few broad principles to apply when knowing when to use dispose()?
A single principle: dispose when the object is disposable.
I don't feel like I understand the basics of knowing when to use dispose().
Dispose all objects that are disposable.
One comment I saw asked if memory is released when a variable goes out of scope, and that got my attention because until I saw the response was no, it doesn't get released just because it goes out of scope, I would have thought that it does get released when it goes out of scope.
Be careful in your use of language. You are confusing scope and lifetime, and you are confusing variables with the contents of the variables.
First: the scope of a variable is the region of program text in which that variable may be referred to by name. The lifetime of a variable is the period of time during the execution of the program in which the variable is considered to be a root of the garbage collector. Scope is purely a compile-time concept, lifetime is purely a run-time concept.
The connection between scope and lifetime is that a local variable's lifetime is often starting when control enters the scope of the variable, and ending when it leaves. However, various things can change the lifetime of a local, including being closed over, in an iterator block, or in an async method. The jitter optimizer may also shorten or extend the life of a local.
Remember also that a variable is storage, and that it may refer to storage. When the lifetime of a local ends, the storage associated with the local might be reclaimed. But there is no guarantee whatsoever that the storage associated with the thing the local refers to will be reclaimed, at that time or ever.
So that's why my question is "What determines when a dispose() is really necessary?"
Dispose is necessary when the object implements IDisposable. (There are a small number of objects that are disposable that need not be disposed. Tasks, for instance. But as a general rule, if it is disposable, dispose it.)
My question is less one of how and more one of when.
Only dispose a thing when you are done with it. Not before, and not later.
When should I dispose my objects in .NET?
Dispose objects when they implement IDisposable, and you are done using them.
How do I know if something falls into the category of what I must dispose?
When it is implementing IDisposable.
I just don't know what objects or things I create require that I am responsible for disposing.
The disposable ones.
most experienced and professional developers know when something they've created needs to be disposed of. I don't understand how to know that.
They check to see if the object is disposable. If it is , they dispose it.
The point of Dispose is to free unmanaged resources". OK, but my question is how do I know by looking at something that it is an unmanaged resource?
It implements IDisposable.
I don't understand how to use that type of explanation to categorize what I need to dispose() and what I don't. There's all kinds of stuff in the .net framework; how do I separate out things that require I dispose() of them? What do I look at to tell me I'm responsible for it?
Check to see if it is IDisposable.
After that, the answer goes on to speak at great length about how to dispose(), but I'm still stuck back at what needs to be disposed.
Anything that implements IDisposable needs to be disposed.
my question is about when, meaning what needs to be disposed(), as opposed to when I'm done with it. I know when I'm done with things, I just don't know which things I'm responsible for when I'm done with them.
The things that implement IDisposable.
I was hoping there is a general principle for what must be disposed rather than a long list of specific items which would not be particularly useful for people like me who are looking for simple guidelines.
The simple guideline is that you should dispose disposable things.
Again, I get it that memory release is important, and also that a lot of experience and expertise goes into learning why and how, but I'm still left struggling to understand what needs to be disposed. Once I understand what I have to dispose(), then I can begin the struggle to learn how to do it.
Dispose things that implement IDisposable by calling Dispose().
So is this still a bad question?
It is a very repetitive question.
Your patience is a kindness.
Thanks for taking this somewhat silly answer in the humour in which it was intended!
WRT scope != lifetime & variables != objects, very helpful.
These are very commonly confused, and most of the time, it makes little difference. But I find that often people who are struggling to understand a concept are not at all well served by vagueness and imprecision.
In VS is it so simple as looking in Object Browser / Intellisense to see if the object includes Dispose()?
The vast majority of the time, yes.
There are some obscure corner cases. As I already mentioned, the received wisdom from the TPL team is that disposing Task objects is not only unnecessary, but can be counterproductive.
There are also some types that implement IDisposable, but use the "explicit interface implementation" trick to make the "Dispose" method only accessible by casting to IDisposable. In the majority of these cases there is a synonym for Dispose on the object itself, typically called "Close" or some such thing. I don't much like this pattern, but some people use it.
For those objects, the using block will still work. If for some reason you want to explicitly dispose such objects without using using then either (1) call the "Close" method, or whatever it is called, or (2) cast to IDisposable and dispose it.
The general wisdom is: if the object is disposable then it does not hurt to dispose it, and it is a good practice to do so when you're done with it.
The reason being: disposable objects often represent a scarce shared resource. A file, for example, might be opened in a mode that denies the rights of other processes to access that file while you have it opened. It's the polite thing to do to ensure that the file is closed as soon as you're done with it. If one process wanted to use a file, odds are pretty good another one will soon.
Or a disposable might represent something like a graphics object. The operating system will stop giving out new graphics objects if there are more than ten thousand active in a process, so you've got to let them go when you're done with them.
WRT implementing IDisposable #Brian's comment suggests in "normal" coding I likely don't need to. So would I only do that if my class pulled in something unmanaged?
Good question. There are two scenarios in which you should implement IDisposable.
(1) The common scenario: you are writing an object that holds onto another IDisposable object for a long time, and the lifetime of the "inner" object is the same as the lifetime of the "outer" object.
For example: you are implementing a logger class that opens a log file and keeps it open until the log is closed. Now you have a class that is holding onto a disposable, and so it itself should also be disposable.
I note that there is no need in this case for the "outer" object to be finalizable. Just disposable. If for some reason the dispose is never called on the outer object, the finalizer of the inner object will take care of finalization.
(2) the rare scenario: you are implementing a new class which asks the operating system or other external entity for a resource that must be aggressively cleaned up, and the lifetime of that resource is the same as the lifetime of the object holding onto it.
In this exceedingly rare case you should first, ask yourself if there is any way to avoid it. This is a bad situation to be in for a beginner-to-intermediate programmer. You really need to understand how the CLR interacts with unmanaged code in order to get this stuff solid.
If you cannot avoid it, you should prefer to not attempt to implement the disposal and finalization logic yourself, particularly if the unmanaged object is represented by a Windows handle. There should already be wrappers around most of the OS services represented by handles, but if there is not one, what you want to do is carefully study the relationship between IntPtr, SafeHandle and HandleRef. IntPtr, SafeHandle and HandleRef - Explained
If you really truly do need to write the disposal logic for an unmanaged, non-handle-based resource, and the resource requires backstopping the disposal with finalization, then you have a significant engineering challenge.
The standard dispose pattern code may look simple but there are real subtleties to writing correct finalization logic that is robust in the face of error conditions. Remember, a finalizer runs on a different thread and can run on that thread concurrent with the constructor in thread abort scenarios. Writing threadsafe logic which cleans up an object while it is still being constructed on another thread can be extraordinarily difficult and I recommend against trying.
For more on the challenges of writing finalizers, see my series of articles on the subject: http://ericlippert.com/2015/05/18/when-everything-you-know-is-wrong-part-one/
A question you did not ask but I will answer anyways:
Are there scenarios in which I should not be implementing IDisposable?
Yes. Many people implement IDisposable any time they wish to have a coding pattern that has the semantics of:
Make a change in the world
Do stuff in the new world
Revert the change
So, for example, "impersonate an administrator, do some admin tasks, revert to normal user". Or "start handling an event, do stuff when the event happens, stop handling the event". Or "create an in-memory error tracker, do some stuff that might make errors, stop tracking errors". And so on. You get the general pattern.
This is a poor fit for the disposable pattern, but that doesn't stop people from writing up classes that represent no unmanaged resource whatsoever, but still implement IDisposable as though they did.
This opinion puts me in a minority; lots of people have no problem whatsoever with this abuse of the mechanism. But when I see a disposable I think "the author of this class wishes me to be polite and clean up after myself when I am good and ready." But the actual contract of the class is often "you must dispose this at a particular point in the program and if you do not then the rest of the program logic will be wrong until you do". That is not the contract I expect to have to implement when I see a disposable. I expect that I have to make a good-faith effort to clean up a resource at my convenience.
If you have an object that implements IDisposable then you must always explicitly call .Dispose() on that object. If it doesn't implement IDisposable then obviously you don't call .Dispose() because you can't.
If you are writing your own objects then the rule as to whether or not to implement IDisposable is simply this: If your object holds references to unmanaged objects OR if it holds references to objects that implement IDisposable then it must implement IDisposable.
The GC never calls .Dispose() for you. You must always do it - either directly or through a finalizer.
The GC may (most likely, but not always) call a finalizer, so you can write a finalizer to call dispose, but be careful that you implement the disposable pattern correctly, and be certain that you understand that the finalizer may not ever run so if your dispose method does something vitally important it might be better to call .Dispose() directly before you lose the reference to the object.
The garbage collector (GC) guarantees that managed memory resources that are no longer used are released before the memory limit is reached.
Let's break that down:
managed: Loosely, this means resources entirely within .NET/CLR. Memory allocated by non-.NET C++ libraries, for example, are not released by the GC.
memory: The GC only provides a guarantee on memory usage. Many other resource types exist, such as file handles. The GC has no logic to ensure file handles are released expediently.
no longer used: This means that all variables with a reference to that memory have ended their lifetime. As Eric Lippert explained, lifetime != scope.
before the memory limit is reached: The GC monitors "memory pressure" and makes sure to release memory when needed. It uses a bunch of algorithms to decide when it is most efficient to do this, but it's important to note that the GC decides when to release resources all on its own (nondeterministically to your program).
This leaves us with several scenarios when relying on the GC is not appropriate:
The object references unmanaged resources (including referencing a managed object that references an unmanaged resource).
The object references a resource other than memory that must be released.
The object references a resource that must be released at a specific point in the code (deterministically).
In any of these cases, the object should implement IDisposable to handle resource cleanup.
Any object instantiated that implements IDisposable must be cleaned up by either calling Dispose or using the using block (which takes care of calling Dispose for you).
The Dispose pattern can be used to clear both managed and unmanaged resources. If you have unmanaged resources in your class, according to the proper IDisposable implementation you must have both Dispose and Finalize methods.
How do I know what GC knows/doesn't?
GC knows/interested only about managed objects. GC is supposed to clear objects those don’t have any strong references. It doesn’t know about your logics. For a simple and obvious example.
Let’s say you have a MainView instance which is a lasting a long time and you create another LittleView that subscribe to an event in the MainView instance.
Then you close the LittleView and it disappears. You know that you don’t need that LittleView instance anymore. But GC doesn’t know if you still need LittleView or not as there is an active event subscription to the MainWindow.
So, GC will not bother to clear LittleView instance from memory. So, what you should do is unsubscribe the event when you close the view. Then GC knows that there are no strong references to the LittleView and it’s reachable.
The post also complicates things saying managed resources may include
unmanaged resources. Wow. This is getting deeper than I initially
imagined. I'm still looking to easily recognize how to know what needs
to be disposed. Is it the case this is a complicated list w/
conditions and context?
That’s correct, managed objects also can have unmanaged resources. All those managed objects have their finalize method to clear umanaged resources.
Wonder why you need finalize method in addition to the Dispose?
Unmanaged resources can create the most dangerous memory leaks as such memory leaks can hold on to memory until you restart the PC. So, they are very bad.
Let’s say there is managed instance InsA with some unmanaged. InsA has implemented the Dispose method in a way to clear unmanaged resources too. But what will happen if you don’t/forget to call the Dispose method? It will never clear that unmanaged memory. That’s why Finalization has come in to the functionality. So, if you forget/don’t call the Dispose, finalization will gurantee to execute the Dispose in a way that it release unmanaged resources.

pattern to release objects in a managed language

In a complex application (involving inversion of control and quite some classes) it is hardly possible to know when a certain object won't be referenced anylonger.
First Question: Suggests the statement above that there is a design flaw in such an application, since there is a pattern saying: "In all OO programming it is about objects using other types of objects to ease up implementation. However: For any object created there should be some owner that will take care of its lifetime."
I assume it is save to state that traditional unmanaged OO programming works like stated above: Some owner will eventually free / release the used object.
However the benefit of a managed language is that in principle you don't have to care about lifetime management anymore. As long an object is referenced anyhow (event-handler...) and from anywhere (maybe not the "owner") it lives and should live, since it is still in use.
I really like that idea and that you don't have to think in terms of owner relationships. However at some point in a program it might get obvious that you want to get rid of an object (or at least mute it in a way as it wouldn't be there).
IStoppable: a suggestion of a design pattern
There could be an interface like "IStoppable", with a "Stop()" method and an "Stopped" event, so that any other object using it can remove their references onto the object. (Therefore would need to unplug their OnStopped event handler within the event handler if that is possible). As a result the object is no longer needed and will get collected.
Maybe it is naive but what i like to believe about that idea is that there wouldn't be an undefined state of the object. Even if some other object missed to unregister itself on OnStopped it will just stay alive and can still get called. Nothing got broken just by removing most references onto it.
I think this pattern can be viewed as an anarchistic app design, since
it is based on the idea that ANY other object can manage the lifetime of an IStoppable
there is no need for an owner
it would be considered as OK to leave the decision of unregistering from an IStoppable to those using it
you don't need to dispose, destroy or throw away - you just stop and let live (let GC do the dirty part)
IDisposable: from scatch and just to check a related pattern:
The disposable pattern suggests that you should still think and work like in unmanaged OO programming: Dispose an object that you don't need anylonger.
using is your friend in a method (very comfortable!)
an own IDisposable implementation is your friend otherwise.
after using it / calling Dispose you shouldn't call it anylonger: undefined behaviour.
implementation and resource centric: it is not so much about when and why, but more about the details of reclaiming resources
So again: In an application where i don't have in mind if anything else but an "owner" is pointing to an object, it is hard to ensure that noone will reference and call it anylonger.
I read of a "Dispose" event in the Component class of .NET. Is there a design pattern around it?
Why would i want to think in terms of Disposables? Why should i?
In a managed world...
Thanks!
Sebastian
I personally don't like the idea of IStoppable, as defined above. You're saying you want any object to manage the lifetime of the object - however, a defined lifecycle really suggests ownership - allowing multiple objects to manage the lifetime of a single object is going to cause issues in the long
IDisposable is, however, a well defined pattern in the .NET world. I wrote an entire series on implementing IDisposable which is a decent introduction to it's usage. However, it's purpose is for handling resource which have an unmanaged component - when you have a managed object that refers to a native resource, it's often desirable to have explicit control of the lifetime of that resource. IDisposable is a defined pattern for handling that situation.
That being said, a proper implementation of IDisposable will still clean up your resources if you fail to call Dispose(). The downside is that the resource will be cleaned up during the object's finalization, which could occur at any arbitrary point after the object is no longer used. This can be very bad for quite a few reasons - especially if you're using native resources that are limited in nature. By not disposing of the resource immediately, you can run out of resources before the GC runs on the object, especially if there isn't a lot of memory pressure in the system.
Ok first I would point out a few things I find uncomfortable about your IStoppable suggestion.
IStoppable raises event Stopped, consumers must know about this and release references. This is a bit complex at best, problematic at worst. Consumers must know where every reference is in order to remove/reset the reference.
You claim "... Nothing got broken just by removing most references onto it.". That entirely depends on the object implementing IStoppable and it's uses. Say, for example, my IStoppable object is an object cache. Now I forget about or ignore the event and suddenly I'm using a different object cache as the rest of the world... maybe that is ok, maybe not.
Events are a horrible way to provide behavior like this due to the fact that exceptions prove difficult to handle. What does it mean when the third out 10 event handlers throws an exception in the IStoppable.Stopped event?
I think what your trying to express is an object that may be 'owned' by many things and can be forcefully released by one? In this case you might consider using a reference counter pattern, more like old-school COM. That of course has issues as well, but they are less of a problem in a managed world.
The issue with a reference counter around an object is that you come back to the idea of an invalid/uninitialized object. One possible way to solve this is to provide the reference counter with a valid 'default' instance (or a factory delegate) to use when all references have been release and someone still wants an instance.
I think you have a misunderstanding of modern OO languages; in particular scope and garbage collection.
The lifetime of the objects are very much controlled by their scope. Whether the scope is limited to a using clause, a method, or even the appdomain.
Although you don't necessarily "care" about the lifetime of the object, the compiler does and will set it aside for garbage collection as soon as it goes out of scope.
You can speed up that process by purposely telling the garbage collector to run now, but that's usually a pointless exercise as the compiler will optimize the code to do so at the most opportune time anyway.
If you are talking about objects in multi-threaded applications, these already expose mechanisms to stop their execution or otherwise kill them on demand.
Which leaves us with unmanaged resources. For those, the wrapper should implement IDisposable. I'll skip talking about it as Reed Copsey has already covered that ground nicely.
While there are times a Disposed event (like the one used by Windows Forms) can be useful, events do add a fair bit of overhead. In cases where an object will keep all the IDisposables it ever owns until it's disposed (a common situation) it may be better to keep a List(Of IDisposable) and have a private function "T RegDisp<T>(T obj) where T:IDisposable" which will add an object to the disposables list and return it. Instead of setting a field to SomeDisposable, set it to RegDisp(SomeDisposable). Note that in VB, provided all constructor calls are wrapped in factory methods, it's possible to safely use RegDisp() within field initializers, but that cannot be done in C#.
Incidentally, if an IDisposable's constructor accepts an IDisposable as a parameter, it may often be helpful to have it accept a Boolean indicating whether or not ownership of that object will be transferred. If a possibly-owned IDisposable will be exposed in a mutable property (e.g. PictureBox.Image) the property itself should be read-only, with a setter method that accepts an ownership flag. Calling the set method when the object owns the old object should Dispose the old object before setting the new one. Using that approach will eliminate much of the need for a Disposed event.

Should I create new Pens/Brushes per Paint request or keep them throughout the application lifecycle?

I have an application that does a lot of drawing, let's pretend it's a Viso-like application. It has objects that have multiple sub-objects that are drawn, things can be connected, resized etc. Currently when I call paint on a particular sub-object or object, I do the following:
using(var pen = new Pen(this.ForeColor))
{
// Paint for this object.
}
I've read conflicting answers that this should be done for an application that is constantly drawing the same thing (maybe just resized, moved etc). Should I store the Pen/Brush with the object and then dispose them all when the application is disposed of, or are they efficient enough to be created/disposed for each paint call (remembering that this is a pretty graphics intense application).
EDIT: There are already two answers that have conflicting answers and this is where I'm not sure to make the switch. Does anyone have any stats on the differences?
You could of course use the Pens and Brushes classes that provide you with objects that are already created by the runtime.
For example, if you want one of the standard colour Pens, you can do this:
var pen = Pens.Red;
Likewise you can do the same with Brushes, if you just want standard solid brush colours:
var brush = Brushes.Red
Using these, you don't need to worry about cleaning them up, disposing it or otherwise.
If you want different colours that you create yourself, for example with a different alpha component, or a gradient brush perhaps, then you still need to create these yourself and clean them up appropriately.
EDIT:
To create and dispose of an array of 100,000 new pens took approximately half a second on my ancient old XP machine, running a test app in Debug mode.
That equates to approximately 5 microseconds per pen. Only you can decide if that is fast enough for you. I would hazard a guess that this time may be largely insignificant with regard to the rest of your operations.
You'll only know the performance impact by testing on your particular application, but the framework doesn't seem to have a problem keeping a few pens around for the life of the application. The first time you call Pens.Black, it creates a black pen and caches it. You get the same object back for future calls, and it's never explicitly disposed (Pens.Black.Dispose() will actually throw an exception). However, you don't want to blindly create pens and leave them to be disposed when the application ends, because you'll be leaking unmanaged memory. A couple of options spring to mind depending on the pattern of usage in your app.
Give each object a private Pen that's created when ForeColor is set and reused for all painting. You should make your object IDisposable so that it can dispose of that Pen properly.
If you're using relatively few distinct colours but lots of objects use each colour, you may not want each object to hold on to its own Pen. Create some cache class that keeps a Dictionary<Color,Pen> and hands them out through a PenCache.GetPen(ForeColor). Like using Pens.Black, you can now forget about disposing them. A problem arises if you use a colour briefly, then don't need it again. The Pen got cached, so you're stuck with it in memory forever. You could keep a Dictionary<Color,WeakReference<Pen>> instead, allowing cached pens to be eventually garbage collected if they're no longer needed.
That last option may be the best general purpose solution, avoiding gratuitous creation and disposal while letting the garbage collector make sure that orphaned pens don't cause too much memory trouble. It may, of course, not be any better in your particular case.
Reusing the same Pen and Brush in operations that will require it many times over is going to be a lot faster than disposing of them each time with using.
I would say for sure that it's a good idea to reuse these as much as possible (and I've seen code comparisons before, but I can't source them right now) but do remember to dispose of them when you are truly finished with them.
Yeah best to test like #fantius suggests, you'll probably find it doesn't really matter - although I'd be temped to keep them open as if I recall correctly they're unmanaged resources and could use up your memory. If you were recreating them every time, you'd need to be especially careful of disposing them properly to avoid memory leaks.
Okay this is an old question, it is probably new for some and has a simple and intuitive solution followed by a detailed explanation.
"Should I hold on to paint resources, like pens and brushes, longer than what is required to preform my painting operation", question is rephrased? The answer is no, you should not in that very context; but why, what does that mean?
When you are painting to a graphics object you are using memory intensive resources for each paint object you create, be it a pen, brush, path, matrix and so on.
Yes, do create pens, create brushes etc. for painting and do myPen.dispose() and immediately following do release all object references to the disposed object by setting that object tree to null such as (myPen = null;) this allows the garbage collector to release unmanaged memory held by these objects without having to wait for the call to object finalize(). See: Garbage collection for more information about how garbage collection works in C#.
Creating too many of these IDisposable class objects and not releasing these objects when finished "Using" them can have serious consequences to your program's operation such as causing possible stack and heap memory exceptions, causing increased CPU usage by having to sort through unnecessary quantities of objects potentially causing slow performance and even a runtime crash if left unchecked. See about the Stack and Heap for more information.
Moral of the story release resources you no longer require; if you must retain resources, bench test the potential effects on performance when you "hold on to resources" hopefully avoiding negative consequences.
Rule of thumb: At the out most, ensure all resources are released upon exiting your "paint event" routine. Preferably, When each of your paint event methods finish so too should any resources implicitly created by that method. Penalty, any object references *passed to those methods like pens and brushes etc. will be held until base object finalize is called which is longer than necessary and can be considered a memory leak in the general terms of the definition. *Pass too many references equals unusable memory for a longer period than what probably is expected or assumed.
Note: Cautiously pass object references like pens and brushes to methods and if doing so implement an IDisposable interface at a class level to perform your painting. Your homework just got more expensive and recommend checking out the IDisposable interface.
Happy painting!

What classes should I use C#'s using statement with?

I've read and I believe I understand what C#'s using statement does (please correct me if I'm wrong): Initializes an IDisposable object as read only to a limited scope (the using block). I know you can initialize before the using and that doesn't limit the scope, but that is advised against here:
http://msdn.microsoft.com/en-us/library/yh598w02.aspx
I'm not always paying attention to what classes are subclasses of what. I'm not too sure what classes inherit from IDisposable. I'm not just curious what classes can be used in a using statement, but what classes would my coworkers expect to find in a using block? What classes should be in a using block? Also, is there really anything wrong with not using a using block and not calling Dispose? Is it just about memory or also stability?
Strictly speaking, any object that implements IDisposable and whose scope is limited to that function should be within a using block. The IDisposable interface exists to allow classes that deal with unmanaged resources (database connections, file handles, window handles, etc.) to dispose of these resources in a timely, deterministic fashion.
There are, in general, three ways in which an IDisposable object is used within a class:
The object is both created and no longer needed within the scope of a single method call. This is quite common, and is when using can (and should) be used.
The object is created by the class (or is passed to the class), and its lifetime extends beyond the scope of a single method call but not beyond the life of the class. For example, your class creates a Stream and needs to use it over the lifetime of the object. In this case, your class should implement IDisposable itself and dispose of the object(s) that you own when your own Dispose method is called. An example of this would be something like System.IO.StreamWriter
The object is passed to the class, but the class doesn't "own" it. This means that the IDisposable object's usable lifetime is beyond the scope of a single method call, and may be beyond the lifetime of your object. In this case, someone else must be responsible for calling Dispose.
The first case is the most common that you'll encounter, which is why the using block exists. It takes care of ensuring that the object will be disposed of, even in the case of an exception.
Some examples:
Stream classes
Database connections/commands
Controls
There's no exhaustive list of classes that implement IDisposable, as that list would be fairly large and filled with classes that you'll likely never encounter. Think about what the class does; does it open some sort of connection or file that needs to be closed? In general, does it acquire some kind of resource that needs to be released? If so, it probably implements it. At a basic level, if the compiler allows you to enclose it in using, then it implements IDisposable.
As to the consequences of not calling Dispose, don't consider it. Call Dispose. True, the defensive standard is that if your class uses unmanaged resources directly, then you should define a finalizer that will call dispose in the event that your object is collected and someone has failed to call it, but that should not be a design choice. Ever, as far as I'm aware.
It's not about memory. It's about other resources such as file handles, database connections etc.
Basically if a class implements IDisposable, that's a signal that you should dispose of it when you're done, because it may have unmanaged resources which would be expensive to leave around. (e.g. your connection pool may run out of connections, or a file handle will stay open, preventing another piece of code from opening the same file again).
You should always call Dispose on any class that implements IDisposable, and this is most easily done via a using block.
This is not just about memory. This is also not just about resources. This is about correctness.
StreamWriter is a famous example. Microsoft has even developed an MDA to catch some cases where programmers forgot to call Dispose. This is more than just memory or resources: in the StreamWriter example, a file being written may be truncated.
I had to track down a nasty bug one time (in my boss' code, actually), where a database transaction was being rolled back... turns out the cause was that Dispose wasn't being called, so it was trying to commit too much to disk when the process exited (there's a timeout for finalizers during process exit). The fix was just a few using blocks.
A third example: Microsoft's Managed ESENT wrapper classes have a "three tier" disposal scheme that requires Dispose to be called in the correct order ("outer" classes last).
So, there are three real-world examples where incorrect behavior will result if Dispose is not called properly. Other classes may exibit similar behavior.
As a general rule, you should always call Dispose.
At least, all class that used non managed resources
There is absolutely a lot wrong with not using a using block and not calling Dispose, you most likely will leak memory and / or resources. Using is a convenience, but you really should call Dispose in any object which class derives from IDisposable.
As far as what classes are disposable, you can probe intellisense yourself, or you'll just learn from experience. Some common ones include Image and its children, in fact most of System.Drawing namespace, plenty of file streams, database connections, etc.
As far as when it should be called - as soon as possible. If you know it's disposable, and you know you're done with it, then call Dispose.
I believe many of the .NET base classes that implement IDisposable implement the disposable pattern, which means that they will be disposed of, properly, when the garbage collector comes to get them. But even so, you should still dispose of things when you're done, because
You may leave a reference hanging around (a leak) and it won't be disposed, or
The GC may not come around for a while.
Additionally, for classes you write yourself, garbage collection does NOT equate to proper disposal for unmanaged resources - a common confusion. The disposable pattern needs to be implemented yourself.
The main reason a class would implement IDisposable is to release non managed resources. The garbage collector will release managed resources as they go out of scope and it sees fit, but it has no knowledge of non managed resources. Calling the Dispose method will explicitly release the resources.
If you do not use a using block or call the Dispose method then you will have a problem with memory leakage, which in turn could cause stability issues.
You should use a using block at all times when dealing with classes that implement IDisposable. Although you may prefer a Try.. Catch.. Finally ensuring that you call Dispose in the finally block so you can deal with exceptions.
The purpose of IDisposable is to enable objects that interact with unmanaged resources (like files, databases, or graphics contexts) to clean up after themselves. A using statement is a convenient shorthand for the following construct
var disposable = new MemoryStream();
try
{
//do some work with the disposable object
}
finally
{
if (disposable!=null)
disposable.Dispose();
}
The problem of course is knowing which objects implement IDisposable...unfortunately there is no automated way to know besides the docs. Although I believe there is an Fxcop setting that will check for IDisposables used outside of a using.
you need not to worry about using what classes under using blocks. If the you have used under using statement doesnot implements IDisposbale then it will show you red/blue wave. So that you can come to knwo that its lacking idisposable interface. And as far as i have used almost all classes of framework has Idisposable implemented. but in custom class , you need to implement
A ready-reckoner of classes to call with using is:
Streams
Database connections, commands and data readers
Readers and Writers
There are many many more classes which you should also Dispose, but those above are frequently used, often in narrow usage scope.
Yes - there are issues with not using using and not calling dispose. A classic is a web app which does not close its connections to a database, effectively sucking resources from the database server as it holds connections open.

IDisposable, Finalizers and the definition of an unmanaged resource

I'm trying to make sure that my understanding of IDisposable is correct and there's something I'm still not quite sure on.
IDisposable seems to serve two purpose.
To provide a convention to "shut down" a managed object on demand.
To provide a convention to free "unmanaged resources" held by a managed object.
My confusion comes from identifying which scenarios have "unmanaged resources" in play.
Say you are using a Microsoft-supplied IDisposable-implementing (managed) class (say, database or socket-related).
How do you know whether it is implementing IDisposable for just 1 or 1&2 above?
Are you responsible for making sure that unmanaged resources it may or may not hold internally are freed? Should you be adding a finalizer (would that be the right mechanism?) to your own class that calls instanceOfMsSuppliedClass.Dispose()?
How do you know whether it is implementing IDisposable for just 1 or
1&2 above?
The answer to your first question is "you shouldn't need to know". If you're using third party code, then you are its mercy to some point - you'd have to trust that it's disposing of itself properly when you call Dispose on it. If you're unsure or you think there's a bug, you could always try using Reflector() to disassemble it (if possible) and check out what it's doing.
Am I responsible for making sure that unmanaged resources it may or may
not hold internally are freed? Should
I be adding a finalizer (would that be
the right mechanism?) to my own class
that calls
instanceOfMsSuppliedClass.Dispose()?
You should rarely, if ever, need to implement a finalizer for your classes if you're using .Net 2.0 or above. Finalizers add overhead to your class, and usually provide no more functionality then you'd need with just implementing Dispose. I would highly recommend visiting this article for a good overview on disposing properly. In your case, you would want to call instanceofMSSuppliedClass.Dispose() in your own Dispose() method.
Ultimately, calling Dispose() on an object is good practice, because it explictly lets the GC know that you're done with the resource and allows the user the ability to clean it up immediately, and indirectly documents the code by letting other programmers know that the object is done with the resources at that point. But even if you forget to call it explicitly, it will happen eventually when the object is unrooted (.Net is a managed platform after all). Finalizers should only be implemented if your object has unmanaged resources that will need implicit cleanup (i.e. there is a chance the consumer can forget to clean it up, and that this will be problematic).
You should always call Dispose on objects that implement IDisposable (unless they specifically tell you' it's a helpful convention, like ASP.NET MVC's HtmlHelper.BeginForm). You can use the "using" statement to make this easy. If you hang on to a reference of an IDisposable in your class as a member field then you should implement IDisposable using the Disposable Pattern to clean up those members. If you run a static-analysis tool like FxCop it will tell you the same.
You shouldn't be trying to second-guess the interface. Today that class might not use an unmanaged resource but what about the next version?
You're not responsible for the contents of an object. Dispose() should be transparent, and free what it needs to free. After that, you're not responsible for it.
Unmanaged resources are resources like you would create in (managed) C++, where you allocate memory through pointers and "new" statements, rather than "gcnew" statements. When you're creating a class in C++, you're responsible for deleting this memory, since it is native memory, or unmanaged, and the garbage collector does not about it. You can also create this unmanaged memory through Marshal allocations, and, i'd assume, unsafe code.
When using Managed C++, you don't have to manually implement the IDisposable class either. When you write your deconstructor, it will be compiled to a Dispose() function.
If the class in question is Microsoft-supplied (ie.. database, etc..) then the handling of Dispose (from IDisposable) will most likely already be taken care of, it is just up to you to call it. For instance, standard practice using a database would look like:
//...
using (IDataReader dataRead = new DataReaderObject())
{
//Call database
}
This is essentially the same as writing:
IDataReader dataRead = null;
try
{
dataRead = new DataReaderObject()
//Call database
}
finally
{
if(dataRead != null)
{
dataRead.Dispose();
}
}
From what I understand, it is generally good practice for you use the former on objects that inherit from IDisposable since it will ensure proper freeing of resources.
As for using IDisposable yourself, the implementation is up to you. Once you inherit from it you should ensure the method contains the code needed to dispose of any DB connections you may have manually created, freeing of resources that may remain or prevent the object from being destroyed, or just cleaning up large resource pools (like images). This also includes unmanaged resources, for instance, code marked inside an "unsafe" block is essentially unmanaged code that can allow for direct memory manipulation, something that definitely needs cleaning up.
The term "unmanaged resource" is something of a misnomer. The essential concept is that of a paired action--performing one action creates a need to perform some cleanup action. Opening a file creates a need to close it. Dialing a modem creates a need to hang up. A system may survive a failure to perform a cleanup operation, but the consequences may be severe.
When an object is said to "hold unmanaged resources", what is really meant is that the object has the information and impetus necessary to perform some required cleanup operation on some other entity, and there's no particular reason to believe that information and impetus exists anywhere else. If the only object with such information and impetus is completely abandoned, the required cleanup operation will never occur. The purpose of .Dispose is to force an object to perform any required cleanup, so that it may be safely abandoned.
To provide some protection against code which abandons objects without first calling Dispose, the system allows classes to register for "finalization". If an object of a registered class is abandoned, the system will give the object a chance to perform cleanup operation on other entities before it is abandoned for good. There's no guarantee as to how quickly the system will notice that an object has been abandoned, however, and various circumstances may prevent an object from being offered its chance to clean up. The term "managed resource" is sometimes used to refer to an object which will have to perform some cleanup before it's abandoned, but which will automatically register and attempt to perform such cleanup if someone fails to call Dispose.
Why should it matter to you?
When possible I wrap the scope of a disposable object in a using. This calls dispose at the end of the using. When not I explicitly call dispose whenever I no longer need the object.
Whether for reason 1 or reason 2 is not necessary.
Yes, you're responsible to call the Dispose method - or better use using statement. If an object is implementing IDisposable, you should always dispose it, no matter what.
using (var myObj = new Whatever())
{
// ..
}
is similar to
{
var myObj;
try
{
myObj = new Whatever();
// ..
}
finally
{
if (myObj != null)
{
((IDisposable)myObj).Dispose();
}
}
} // object scope ends here
EDIT: Added try/finally thanks to Talljoe - wow, that's complicated to get it right :)
EDIT2: I am not saying that you should use the second variant. I just wanted to show that "using" is nice syntactic sugar for a bunch of code that can get quite messy and hard to get right.
One piece that is missing here is the finalizer - my habit has been if I implement IDisposable I also have a finalizer to call Dispose() just in case my client doesn't. Yes, it adds overhead but if Dispose() IS called than the GC.SuppressFinalize(this) call eliminates it.

Categories