14
votes

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);
    }
}
7
well, the first two sentences are...Peter Lillevold
perhaps too much... guess I just needed to get my frustrations out :)Peter Lillevold
Its comunity wiki...so why does it matter if its a question or not? Wiki is knowledge/informational, etc.jrista
yeah this is a question. the question being, what does everyone think? do they agree? are there better ways?andy
@jrista: good point, only noticed after you posted your commentandy

7 Answers

24
votes

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.

6
votes

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.

5
votes

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).

4
votes

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.

2
votes

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.

0
votes

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:

  1. A class declaration that would cause a particular method to be invoked if an exception throws out of its constructor.
  2. 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.

-1
votes

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.