fearofawhackplanet
fearofawhackplanet

Reputation: 53396

static IDisposable dictionary pattern

I have a situation like below in a web application. I just wanted to check that it is a good pattern. Could something happen that meant my dictionary was corrupt (some members were disposed and some not, for example)? Have I implemented this idea correctly?

static IDictionary<string, IDisposable>() _map;

Application_Start()
{
    if (_map == null)
    {
         _map = new IDictionary<string, IDisposable>();
         _map.Add(...);
         _map.Add(...);
    }
}

Application_End
{
    if (_map != null)
    {
        foreach (var m in _map)
        {
            m.Value.Dispose();
        }
        _map = null;
    }
}

Upvotes: 2

Views: 1332

Answers (2)

Massif
Massif

Reputation: 4433

In addition to what other people have said, there's nothing stopping someone calling Dispose on one of the objects in your dictionary - so it'd be pretty easy for you to have a mix of disposed and undisposed objects.

Of course, if you implement IDisposable properly (i.e. the object checks if it's been disposed) then it might not (but probably will) matter if objects are disposed prematurely...

I can't see that it makes much sense to do this, disposing things as the application ends won't really buy you anything as you're past the point of caring about holding onto unmanaged resources. IDisposable is more about releasing unmanaged resources as soon as possible. Greater minds might correct me, but I'm pretty sure once your application is unloaded, unmanaged resources are freed by the OS anyway.

Upvotes: 2

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174329

I see the following problem:
Removing an object from the map during the runtime of the application doesn't dispose it. You will have to do that manually. The same is true for replacing an object in the map.

UPDATE:
The following will leave undisposed objects around:

_map[key] = new DisposableObject();

The object that was previously identified by key will never be disposed.

About the whole concept:
It doesn't make too much sense. The .NET runtime frees all memory of your application when it exits. So, implementing IDisposable on objects that live as long as the application itself seems to be unneeded, unless they hold references to unmanaged resources like a open file handle.

Upvotes: 5

Related Questions