views:

1442

answers:

6

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);
    }
}
+5  A: 

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

Noldorin
I state that "IDisposable by hand...for unmanaged resources", though I would like to see this scenario also supported in a more declarative way. Perhaps through a ~~MyDisposableThing destructor :)
Peter Lillevold
Arguably, autoproperties removed more boilerplate code when you have a lot of properties, but still only three lines of code per property. The dispose pattern requires much more code per class. So in cases where you have many classes that requires IDisposable the impact of a new keyword would be quite large.
Peter Lillevold
A: 

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.

Chris
I don't think that's what the OP is trying to say. He's simply making the point about the level of boilerplate required. IDisposable classes would clearly be demarcated using a keyword (and thus treated differently from ordinary classes) in his example.
Noldorin
@Chris: That's why the topic is on the Dispose method, which does have precise execution time.
Jimmy
+21  A: 

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.

Eric Lippert
Again, the example of autoproperties are IMO mere convenience. Yet it is useful in that it solves the problem of inconvenience and code readability. Elevating the disposable pattern would not only solve inconvenience and code clutter, it would also help developers do the right thing. Certainly, it will not bring any new rich scenarios to the table, it will make code more expressive and safer which is at least a valuable scenario.
Peter Lillevold
Indeed, autoprops are pretty much just a convenience. I was quite astonished that they made it in to C# 3.0. The design, implementation, testing and documentation costs of autoprops turned out to be low enough to justify it, but still, it was surprising.
Eric Lippert
The benefit of elevating disposability out the the pattern and in to the language proper is that it allows the pattern to be implemented correctly. This is the single biggest problem I see with implementations of the dispose pattern...people think that by implementing IDisposable they are implementing the pattern, which isn't really the case. It also has the potential for allowing other patterns to be used that make use of the using semantics, which are very valuable but don't always have anything to do with disposability.
Scott Dorman
I am surprised Eric is surprised about autoprops :) The difference that they make is that it's actually easy enough to implement properties now (instead of fields) that even lazy programmers will use them where they should be used. That is a MASSIVE difference, which IMO is worth all that implementation effort. This proposal would make lazy programmers write properly disposable classes and properly dispose of them.
romkyns
Oh, I agree that they are a lovely feature and totally worth it. But for scheduling C# 3 we were strongly devoted to the proposition that anything which might slip LINQ would be aggressively cut. Auto props and partial methods just barely squeaked in there.
Eric Lippert
It would be interesting if the C# compiler had an extensibility feature, with compile time hooks where user code can participate, like in Boo or Nemerle. This way, the language spec would be complete, and all the new "features" would be developed as compiler extensions, either by Microsoft or third parties. Patterns could be elevated to the language level. But, this might be really hard to achieve properly, and the tooling support would have to evolve as well: if I create a new extension "keyword", like `disposable`, then I want Visual Studio to also know about it.
Jordão
+4  A: 

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.

Greg Beech
Valid points here. Having automatic generation of guards is not feasible imo, since the compiler would then have to "know" about which variables should be guarded. I can see that getting overly complicated and too much magic going on.The disposable keyword should generate an IsDisposed property though so that it would be easy to create guards. And yes, this should be part of the deal so that users wont have to track the disposed state themselves.
Peter Lillevold
+1  A: 

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.

Daniel Earwicker
A: 
supercat