I've recently inherited an asp.net project that is running into memory leaks. In my investigation I noticed there are a lot of custom classes implementing IDisposable, but they aren't employing "using" when called. I've been fixing these issues, but one use case I was curious about was putting static methods on the class. Something like this:
public class ImDisposable : IDisposable{
public static GetList(string search){
//doStuff
}
//implement IDisposable
}
public class UseDisposable{
public void GetList(string search){
var list = ImDisposable.GetList(search);
//do stuff
}
}
I've never seen anything like this done, and I was curious how the GC handles this scenario. Thanks.
Static methods don't rely on any particular instance, and therefore they shouldn't be able to access instance members of your class which might tie up un-managed resources.
You need not consider them when thinking about Disposing of resources
On a related note, The existence of methods has little to do with IDisposable either. It doesn't dispose of the "methods" per-se, It disposes of unmanaged resources that an instance of the class might use. (such as open file streams)
You may be confusing memory leaks and garbage collection... just because you're not calling Dispose() doesn't mean you'll have a leak. You get a leak when:
(1) The class you didn't dispose has a handle to unmanaged resources, e.g. a file stream. Theoretically, if a class implements IDisposable, it has unmanaged resources, but I've seen enough empty dispose methods that I'm jaded. I.E. for static classes/members, unless you have a static variable that needs disposed, that's not your memory leak.
Also, static members would only ever have one instance, regardless of how many classes you instantiate, and you can't really have a leak when no new instances are ever created.
(2) You keep object references when you don't need/mean to... good example would be event listeners, especially those connected as a lambda. Not calling Dispose() on a database connection is also considered a leak, even though Dispose() simply returns the connection to the connection pool.
Also keep in mind that a growing memory footprint is not necessarily a leak. Garbage Collection is only performed when the .NET runtime deems it necessary... if there's still plenty of memory available, there's no need to GC.
Highly simplified overview; I'm mostly saying that nothing static is related to your memory leak. There's a good article on pinning down memory leaks here
Your question is a bit vague.
You may see the book CLR via C# by Richter for explanation about the garbage collection. Though my feeling is that your question is more about the interaction between a static method in a non-static class and the garbage collector. The above aforementioned book covers that too.
In general, a static method that allocates a resource will behave in a similar manor to a non-static method that allocates resources. However, the IDisposable interface will operate on the instance of the class. Therefore, your
static GetList(..)
method should not use resources that need the IDisposable implementation to free.
Related
Microsoft design guidelines mention Dispose pattern and scenarios how to use it:
DO implement the Basic Dispose Pattern on types containing instances
of disposable types. See the Basic Dispose Pattern section for details
on the basic pattern.
Later, they show the Basic Dispose Pattern as follows:
public class DisposableResourceHolder : IDisposable {
private SafeHandle resource; // handle to a resource
public DisposableResourceHolder(){
this.resource = ... // allocates the resource
}
public void Dispose(){
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing){
if (disposing){
if (resource!= null) resource.Dispose();
}
}
}
My questions are:
Why do we need to implement Dispose(bool) if it has just a single call with parameter true? It could be easily simplified to just parameterless Dispose() {resource?.Dispose();}. Note we don't need finalizer here because objects we are referencing are managed and have their own finalizers, so they won't be leaked.
Why do they recommend to call GC.SuppressFinalize(this) while not having finalizer? GC anyway wouldn't call finalizer because it does not exist!
The only case when I see the need of Dispose(bool) is when we really have some unmanaged references, which does not implement IDisposable nor finalizer (like shown in this article). But then the meaning of bool disposing would be bool includingManagedResources. So why is it named so misleading 'disposing' to what it should do in fact?
Other classes could inherit from your class. Considering that the deriving class also holds unmanaged resources (recommended or not), this class should then add the finalizer calling Dispose(false). If your class was sealed I would agree with you.
Because the method void Dispose() should not be virtual following the guidelines from Microsoft and thus deriving classes would then have no chance to suppress finalization after disposal. Your implementation might not need a finalizer, but probably deriving classes do.
It's called disposing for no specific reason in my opinion. I personally would rename it as well.
Anyway, from my point of view it is not a good approach to mix owning managed and unmanaged resources. As already mentioned in the comment even Microsoft recommends to encapsulate unmanaged resources into managed ones thus the cases where you need to implement finalizers are probably rare. I cannot remember when I did this myself the last time.
I am also not sticking to the implementation from the guidelines for multiple reasons, like misleading naming or because it's hard to understand. An alternative approach would be this answer.
There is a LOT of info around about the "standard full" IDisposable implementation for disposing of unmanaged resources - but in reality this case is (very) rare (most resources are already wrapped by managed classes). This question focuses on a mimimal implementation of IDisposable for the much more common "managed resources only" case.
1: Is the mimimal implementation of IDisposable in the code below correct, are there issues?
2: Is there any reason to add a full standard IDisposable implementation (Dispose(), Dispose(bool), Finalizer etc) over the minimal implimentation presented?
3: Is it OK/wise in this minimal case to make the Dispose virtual (since we are not providing Dispose(bool))?
4: If this minimal implementation is replaced with a full standard implementation that includes a (useless, in this case) finalizer - does this change how the GC handles the object? Are there any downsides?
5: The example includes Timer and event handlers as these cases are particularly important not to miss as failing to dispose them will keep objects alive and kicking (this in the case of Timer, eventSource in case of the event handler) until the GC gets round to disposing them in its time. Are there any other examples like these?
class A : IDisposable {
private Timer timer;
public A(MyEventSource eventSource) {
eventSource += Handler
}
private void Handler(object source, EventArgs args) { ... }
public virtual void Dispose() {
timer.Dispose();
if (eventSource != null)
eventSource -= Handler;
}
}
class B : A, IDisposable {
private TcpClient tpcClient;
public override void Dispose() {
(tcpClient as IDispose).Dispose();
base.Dispose();
}
}
refs:
MSDN
SO: When do I need to manage managed resources
SO: How to dispose managed resource in Dispose() method in C#
SO: Dispose() for cleaning up managed resources
The implementation is correct, there are no issues, provided no derived class directly owns an unmanaged resource.
One good reason to implement the full pattern is the "principle of least surprise". Since there is no authoritative document in MSDN describing this simpler pattern, maintenance developers down the line might have their doubts - even you felt the need to ask StackOverflow :)
Yes it's OK for Dispose to be virtual in this case.
The overhead of the unnecessary finalizer is negligible if Dispose has been called, and is correctly implemented (i.e. calls GC.SuppressFinalize)
The overwhelming majority of IDisposable classes outside the .NET Framework itself are IDisposable because they own managed IDisposable resources. It's rare for them to directly hold an unmanaged resource - this only happens when using P/Invoke to access unmanaged resources that aren't exposed by the .NET Framework.
Therefore there is probably a good argument for promoting this simpler pattern:
In the rare cases that unmanaged resources are used, they should be wrapped in a sealed IDisposable wrapper class that implements a finalizer (like SafeHandle). Because it's sealed, this class doesn't need the full IDisposable pattern.
In all other cases, the overwhelming majority, your simpler pattern could be used.
But unless and until Microsoft or some other authoritative source actively promotes it, I'll continue to use the full IDisposable pattern.
Another option is to refactor your code to avoid inheritance and make your IDisposable classes sealed. Then the simpler pattern is easy to justify, as the awkward gyrations to support possible inheritance are no longer necessary. Personally I take this approach most of the time; in the rare case where I want to make a non-sealed class disposable, I just follow the 'standard' pattern. One nice thing about cultivating this approach is that it tends to push you toward composition rather than inheritance, which generally makes code easier to maintain and test.
My recommended Dispose pattern is for a non-virtual Dispose implementation to chain to a virtual void Dispose(bool), preferably after something like:
int _disposed;
public bool Disposed { return _disposed != 0; }
void Dispose()
{
if (System.Threading.Interlocked.Exchange(ref _disposed, 1) != 0)
Dispose(true);
GC.SuppressFinalize(this); // In case our object holds references to *managed* resources
}
Using this approach will ensure that Dispose(bool) only gets called once, even if multiple threads try to invoke it simultaneously. Although such simultaneous disposal attempts are rare(*), it's cheap to guard against them; if the base class doesn't do something like the above, every derived class must have its own redundant double-dispose guard logic and likely a redundant flag as well.
(*) Some communications classes which are mostly single-threaded and use blocking I/O allow Dispose to be called from any threading context to cancel an I/O operation which is blocking its own thread [obviously Dispose can't be called on that thread, since that thread can't do anything while it's blocked]. It's entirely possible--and not unreasonable--for such objects, or objects which encapsulate them, to have an outside thread try to Dispose them as a means of aborting their current operation at just the moment they were going to be disposed by their main thread. Simultaneous Dispose calls are likely to be rare, but their possibility doesn't indicate any "design problem" provided that the Dispose code can act upon one call and ignore the other.
I am working on a "learning program" and using the Code Rush refactoring tool with my learning. With the latest update of Code Rush it has been recommending implementing IDisposable to my programs. I know what MSDN says about IDisposable and I have a real basic understanding of what it does but because I don't know all the implications of implementing it I have been ignoring the recommendation. Today I decided to learn more about it and went along with the recommendation.
This is what it added to my program.
class Program : IDisposable
{
static Service _proxy;
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
if (_proxy != null)
{
_proxy.Dispose();
_proxy = null;
}
}
~Program()
{
Dispose(false);
}
So my questions is this. Does that do everything I need to do to get the advantage of IDisposable or do I need to do something in code to make it work? I put a break points on that and never reached it through the debugger so either it was not needed or I am not using it the way it was intended. Can someone please shed some light on what this is doing for me or how I should use it so it does do something for me?
In this case, CodeRush is suggesting you implement IDisposable because your class encapsulates an IDisposable resource (it's seeing _proxy, though that's not entirely a good thing since it's static). Code Rush thinks that there is a type that you're using which should be explicitly cleaned up, but you're not providing a way to do it via your class.
That being said, IDisposable is tricky - and this is one case where the generated code is not really a good implementation (even if _proxy were an instance variable). I would recommend not using the destructor in this case. It will cause performance issues in the GC, and in this case, doesn't help with the safety, as the encapsulated resource should handle that the case where you forget to call Dispose() for you. For details, see my series on IDisposable, and, in particular, encapsulating an IDisposable class.
In addition, this class shouldn't implement IDisposable (unless there is some other reason to do so) given the code above, as the _proxy resource is static. Disposing a static resource from an instance is likely to cause problems, at least in a general case. (In this case, it's obviously not problematic, but it's not a good practice...) Typically, a static variable has a very different lifetime than an instance member, so automatically disposing of it would be inappropriate.
In a properly-written program, at any given time, for every object that could possibly have a meaningful implementation of IDisposable, there will be some entity that is responsible for ensuring that IDisposable.Dispose will get called on that object sometime between the last "real use" of that instance and its ultimate abandonment. In general, if an object Foo is going to hold references to objects which implement IDisposable, at least one of the following scenarios should apply:
Some other object will also hold the reference for at least as long as Foo needs it, and will take care of calling Dispose on it, so Foo should let the other object take care of the Dispose.
The object holding the reference will be the last thing to use the IDisposable object in question; if Foo doesn't call Dispose, nothing else will. In that scenario, Foo must ensure that that other object's Dispose method gets called once it (Foo) is no longer needed, and before it is abandoned. The most idiomatic way to handle this is for Foo to implement IDisposable.Dispose, and for its Dispose method to call Dispose on the IDisposable objects to which it holds the last useful references.
There are some scenarios where a class designer might not know whether its class is going to hold the last useful reference to an IDisposable object. In some cases, this issue may be resolved by having a class constructor specify whether a IDisposable passed to the constructor is being "lent" or "given". Other cases may require the use of reference-counting wrappers or other complex techniques.
i've read msdn and various posts about dispose pattern, and there are still a couple of things i don't understand. I've written the following code to test the dispose pattern. Please note that there aren't unmanged resources, i'm using vs2008 and .net 3.5 :
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void tryDispose()
{
//test 1 : allocate resource and leave manage it to gc
BL.myclass df = new BL.myclass();
//test 2 : try to force garbage collecting
//GC.Collect();
//test 3 : call dispose myself
//using (BL.myclass df = new BL.myclass())
//{
//}
}
private void button1_Click(object sender, EventArgs e)
{
tryDispose();
}
this is my disposable class:
class myclass: IDisposable
{
private StronglyTypedDs myDS;
private bool _disposed;
public myclass()
{
using (myDSTableAdapter docDocadpt = new myDSTableAdapter())
{
myDS = new StronglyTypedDs();
docDocadpt.Fill(myDS.TheTable);
}
}
#region IDisposable Members
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
~myclass()
{
Dispose(false);
}
protected virtual void Dispose(bool disposing)
{
if (!_disposed)
{
if (disposing)
{
if (myDS != null)
myDS .Dispose();
myDS = null;
}
}
_disposed = true;
}
#endregion
}
The results are :
test 1a - just instantiating myclass, the destructor is commentend since myclass doesn't contains unmanaged resources : myclass.dispose is not called, even if i close the application (whose dispose is executed instead) . So what's the state of the dataset once i close the application ?
test 1b - uncommenting destructor, it's ok all disposes are called when i close the application.
test 2a and 2b - i do the above test just calling gc.collect : the behaviour is identical to test 1a and 1b respectively
test 3 - everything works fine (of course)
many posts says that, if myclass doesn't contains unmanaged resources, i don't need to add the destructor; yet in my tests , if i don't add the destructor , myclass.dispose doesn't get called when i close the application. I haven't waited for the gc to run by itself (if i remember correctly gc.collect doesn't guarantes the class instance is deallocated) to check if it will call myclass.dispose .
So what's the correct implemention : always define e destructor or avoid it if myclass contains only managed resources ?
If i had filled all generations levels, would had the gc called myclass dispose or not without having implemented a destructor?
Finally i've noticed that if i define a destructor , but don't declare the class as implementing IDisposable, the disposing chain works anyway. This could make sense since the destructor might be translated to finalize in IL. But i find it really confusing : is it some kind of "implicit" interface implementation i don't know? gc can dispose the item but users can't
thank you in advance
Stefano
Trust your Garbage Collector. Managed resources will get cleaned up, eventually. There is no need for a finalizer or implementing IDisposable unless you have some external resource that needs to be released.
This typically means that you only should implement IDisposable when you either:
Are wrapping a native resource. (In this case, you probably also want a finalizer.)
Are encapsulating a class which implements IDisposable. (In this case, you want IDisposable, but don't need to implement a finalizer/destructor.)
Part of the confusion with IDisposable, in my opinion, is that it covers quite a few use cases, and the proper implementation changes depending on what you're doing (ie: wrapping native resources, wrapping other IDisposable classes, or using Factored types). To address this, I've written a multiple part series on IDisposable - it might help clarify some of this for you.
The correct pattern is to only use a finalizer when your class contains unmanaged resources. As to relying on the GC to dispose of your managed objects, don't. The IDisposable contract makes it clear that this object needs to be disposed.
Ok i think i've understood, referring to my example its correct to implement a dispose because the dataset is global to my class and implements IDisposable , while i don't need the finalizer because there aren't unmanaged resources.
Even if i "forget" to dispose some managed resource in my class dispose method, the gc will collect it at some point. The dispose method is just an utility i provide to other classes/developers for managed resources, a must with the finalizer if i wrap unmanaged resources .
i'll read the articles you have provided asap, but in the mean time i've the last question : when gc will free memory owned by my class and its resources ? when someone calls dispose or when it will run (it will free memory instead of moving it to next generation ) ?
thank you everybody for your answers and examples
I wrote a brief seris entitled How to Implement IDisposable and Finalizers: 3 Easy Rules. It describes a much simpler approach that Microsoft themselves have followed since the 2.0 version of the BCL.
The "official" pattern is needlessly complex and needlessly confusing.
Your code is correct, you've implemented it exactly like it is documented in the MSDN library.
You'll need to take a second look though. Reason what happens when the destructor (aka finalizer) runs. The disposing argument will be false, the protected Dispose method does nothing. This is entirely normal, finalizers should only ever release unmanaged resources. You don't have any. It is extraordinary rare to ever have an unmanaged resource in your own code. They belong in the nice wrapper classes available in .NET to turn an unmanaged operating resource into a nice managed class. If you find yourself thinking you need a finalizer, you'll be wrong 99.99% of the time. Even if you do wrap an unmanaged resource, you should use one of the SafeHandle wrappers. And rely on their finalizers.
Okay, you want to get rid of the destructor. It isn't healthy to leave it in, it keeps the object in memory longer than necessary. When you do, you'll cut it down to:
public void Dispose()
{
if (myDS != null) myDS.Dispose();
}
Which is the boiler-plate implementation of most any Dispose() method, just call the Dispose method of members of the class. You can completely omit it if you don't have any members with a Dispose() method.
Next, you do misunderstand how the Dispose() method gets called. It is not automatic. Which is the point of having it in the first place, releasing resources automatically is already taken care of by the garbage collector. The Dispose() method is there for you to call, either with the using statement or calling it directly. So that you can release the resource early instead of waiting for the garbage collector finalizer thread to get around to it. Which can take a while. Call it when you know that your program won't be using the object anymore.
If your DataSet is actively used by the form then you cannot dispose it until the form closes. Call the class' Dispose() method in a FormClosed event handler. Or, better, open the form's Designer.cs file, cut-and-paste the Dispose() method you find in there and move it to the form's source code file. And add the dispose call. I know that's a bit confuzzling, but the only time it's okay to edit the designer file.
The main purpose of IDisposable is to have a consistent standard interface you can dispose of unmanaged resources with, that is if you didn't do something to ensure Dispose() was called these resources would hang around after the app was closed. Also understood by the using() syntax, that is using will implement the following block for you:
DisposableType someDisposable = new DisposableType();
try
{
// Do whatever
}
finally
{
((IDisposable)someDisposable).Dispose();
}
This is all implemented in a nice design like so:
using(DisposableType someDisposable = new DisposableType())
{
// Do whatever
}
What are your opinions on how disposable objects are implemented in .Net? And how do you solve the repetitiveness of implementing IDisposable classes?
I feel that IDisposable types are not the first-class citizens that they should've been. Too much is left to the mercy of the developer.
Specifically, I wonder if there should'nt have been better support in the languages and tools to make sure that disposable things are both implemented correctly and properly disposed of.
In C# for instance, what if my class that needs to implement the disposable semantics could be declared like this:
public class disposable MyDisposableThing
{
~MyDisposableThing()
{
// Dispose managed resources
}
}
The compiler could in this case easily generate an implementation of the IDisposable interface. The destructor ~MyDisposableThing could be transformed into the actual Dispose method that should release managed resources.
The intermediate C# code would look like this:
public class MyDisposableThing : IDisposable
{
private void MyDisposableThingDestructor()
{
// Dispose my managed resources
}
~MyDisposableThing()
{
DisposeMe(false);
}
public void Dispose()
{
DisposeMe(true);
GC.SuppressFinalize(this);
}
private bool _disposed;
private void DisposeMe(bool disposing)
{
if (!_disposed)
{
if (disposing)
{
// Call the userdefined "destructor"
MyDisposableThingDestructor();
}
}
_disposed = true;
}
}
This would make for much cleaner code, less boilerplate disposing code, and a consistent way of disposing managed resources. Implementing IDisposable by hand would still be supported for edge cases and unmanaged resources.
Ensuring that instances are properly disposed is another challenge. Consider the following code:
private string ReadFile(string filename)
{
var reader = new StreamReader();
return reader.ReadToEnd(filename);
}
The reader variable never outlives the scope of the method but would have to wait for the GC to dispose it. In this case, the compiler could raise an error that the StreamReader object was not explicitly disposed. This error would prompt the developer to wrap it in a using statement:
private string ReadFile(string filename)
{
using (var reader = new StreamReader())
{
return reader.ReadToEnd(filename);
}
}
An oft-stated principle is that "design patterns are needed to address language deficiencies". This is an example of that principle. We need the disposable pattern because the language doesn't give it to you.
I agree that disposability could have been elevated out of the "pattern" world and into the C# language proper, as we did with, say, property getters and setters (which are standardizations of the pattern of having getter and setter methods), or events (which standardize the idea of storing a delegate and calling it when something interesting happens.)
But language design is expensive and there is a finite amount of effort that can be applied to it. Thus we try to find the most useful, compelling patterns to put into the language proper. And we try to find a way that does so in a way that is not merely convenient, but actually adds more expressive power to the language. LINQ, for example, moves the concepts of filtering, projecting, joining, grouping and ordering data into the language proper, which adds a lot of expressive power to the language.
Though this is certainly a good idea, I don't think it meets the bar. It would be a nice convenience, I agree, but it doesn't enable any really rich new scenarios.
In addition to the other answers, there is the problem of how much should this implement and what should people expect from it? Say I declared my class like this:
public disposable class MyClass
{
readonly AnotherDisposableObject resource = new AnotherDisposableObject();
~MyClass()
{
this.resource.Dispose();
}
public void DoStuff()
{
this.resource.SomeMethod();
}
}
Then what would you expect to happen if a caller called DoStuff after the instance had been disposed? Should the compiler automatically insert something like
if (this.disposed) throw new ObjectDisposedException();
at the start of every method because you have declared the class as disposable?
If so then what about cases where methods are explicitly allowed to be called after an object is disposed (e.g. MemoryStream.GetBuffer)? Would you have to introduce a new keyword that indicated this to the compiler, e.g. public useafterdispose void ...?
If not then how do you explain to people that the new keyword implements some of the boiler-plate code for you, but that they still need to write code to check whether the object is disposed in each method? Moreover, how can they even check this, because all the state information about whether the object has been disposed is auto-generated! Now they need to track their own flag in the ~MyClass method which undoes half the work the compiler should be doing for you.
I think as a specific language pattern there are too many holes in the concept, and it only attempts to solve one specific problem. Now what could solve this entire class of problem in a general-purpose fashion is mixins (i.e. a Disposable mixin) and this language feature would be generally reusable for different concepts (e.g. Equatable mixin, Comparable mixin, etc.). That's where my money would go.
Personally, I consider the support for IDisposable to be quite decent in the current version of .NET. The presence of the using keyword pretty much makes it into a first-class construct for me.
I do admit there is a certain amount of boilerplate code involved, but not enough to warrant a new language features. (Auto-implemented properties was a good example of a feature that was begging to be introduced.) You've missed out an important point in your post that this "boilerplate" code is not always what you need. Mainly, you need to dispose unmanaged resources outside of the if (disposing) block.
Of course, the destructor (~MyDisposableThing) and parameterless Dispose() method are genuinely boilerplate and could be eliminated by the user of a language keyword, as you suggest - but again I'm not sure the introduction of an actual new keyword is all that necessary for a few lines of code.
I certainly see the point you are making here, and do sympathise with it to some degree. (I'm sure no coder would complain if your suggestion becamse part of the language specification.) However, it's not likely to convince the .NET development team when there are a rather limited number of lines of code anyway, some of which are arguably fairly context-specific (and thus not boilerplate).
I completely agree that IDisposable needs better language suppprt. Here's my variant of it from a while ago. The details are probably wrong, but C++/CLI serves as a pretty good model for this. Unfortunately it confuses the hell out of C# programmers when I show them examples in C++/CLI. But it already does "the right thing" in terms of implementation; we would just need a new syntax in C#.
Even the simplest Windows Forms application has a Dispose method in it, which is generated by a wizard and is fragile in the face of inexpert changes. The idea of composing components together such that one component can "own" several others is so fundamental that IDisposable is practically unavoidable, and unfortunately it seems to take several pages of most books to explain how to implement it correctly.
The existing using statement takes care of the client side. Where we need more language support is on the implementation side.
Some of the fields of a class are references to things that the class "owns", and some not owned. So we have to be able to mark a field as owned.
Also, it would be a very bad idea to automatically generate a finalizer. Most often, a class will own other objects that implement IDisposable. Not all classes are thread safe, nor should they need to be. If they are called from a finalizer, that happens on another thread, forcing them to be thread safe. This is probably the one area around IDisposable that causes the most confusion - a lot of people read the books and come away with the mistaken impression that you have to write a finalizer on an object that supports IDisposable.
I realize this is an old thread but there is something that has been overlooked.
Dispose pattern in both C# and Java break the fundamental reason for not having a deterministic destructor.
MyObject A = new MyObject()
MyObject B = A;
A.Dispose();
What is the state of B now? What if the owner of B didn't really want it disposed. You now have the same issue in C++ where you have to keep track of all the references of objects you are holding on to.
IDisposable is only truly valid within the context of using() and ensuring resource cleanup if an exception occurs.
There are design patterns to do this but it isn't IDisposable
#Peter Yes I am arguing that the Dipsosable pattern has a fault. When implemented the Disposable pattern isn't normally meant to just dispose OS resources with the idea of being able to continue using the object that was disposed. By using the Disposable pattern outside of a try{} finally{} in Java or using() in .NET you break one of the reasons of having a GC. I am not saying memory will leak. I am saying you can now have other parts of the code that have a reference to an Object that has been disposed. Now the onus is back on the developer to check if an object has been disposed before each call, or at the very least catch a ObjectDisposedException.
Lets look at a silly example:
FileStream stream = new FileStream (#"c:\mylog.txt");
logger.setStream (stream);
Who is supposed to invoke .Dispose()? It may not be obvious that the logger is now aquiring ownership of the file stream. Let's say the stream was created somewhere else outside of the developer knowing it will be set as the logging stream.
if we were to add one line, we would break the logger
using (FileStream stream = new FileStream (#"c:\mylog.txt"))
{ logger.setStream (stream); }
or
FileStream stream = new FileStream (#"c:\mylog.txt");
logger.setStream (stream);
stream.Dispose();
The Disposable pattern does not reference count for resources. The developer now has to be conscious of who owns the object and who is responsible for cleaning it up. The real problem is that when Dispose() is invoked the normal behavior is to invalidate the whole object preventing it from being used.
IMHO, the .net languages have a major shortcoming in their handling of iDisposable, which is that there is no nice way of handling initializers that throw exceptions. Unless one 'leaks' a copy of the object under construction or the disposable objects therein, there's no way to clean up any iDisposable objects which were created (either in an initializer, or a base-level constructor) before an initializer throws.
Two features I would like to see toward that end:
A class declaration that would cause a particular method to be invoked if an exception throws out of its constructor.
A field declaration which would indicate that the field should have .Dispose called upon it if some special private method or keyword is used on the object.
BTW, I would also like to see a declaration available for structure methods which would indicate that the method alters the underlying structure. Use of such methods would be forbidden on structure rvalues, and use of such methods on structure properties would generate a read-modify-write sequence.
Okay you need to understand the difference between managed and unmanaged memory.
Put simply, c++ style destructors wouldn't work in the managed world of c# because there's no guarantee when the object gets garbage collected, hence you would never know when the destructor would get called, which would make things very unpredictable.
As opposed to c++, when destructors get called as soon as the class goes out of scope, so you can guarantee when it gets called.
This is the reason why c# can't have destructors.