views:

793

answers:

3

In ASP.NET if items are left in the session state that Implement IDisposable but are never specifically removed and disposed by the application when the session expires will Dispose be called on the objects that any code in Dipose() will execute?

+2  A: 

If the IDisposable pattern is implemented properly, then yes (i.e. the class's destructor will take care of disposing the object). I don't believe the ASP.NET session manager makes any guarantees about explicitly calling Dispose() on classes implementing IDisposable.

Note that despite Mark's aggressive objections, I am not suggesting "routinely" adding finalizers. I am simply suggesting that if you want the Dispose method on your object called when the session expires, this is a viable option.

Sean Bright
A finalizer is *not* a correct IDisposable implementation; rather, something with a finalizer may often also be IDisposable. But an IDisposable object shouldn't have a finalizer just because it is IDisposable.
Marc Gravell
I didn't think that was "aggressive" - simply that a finalizer has nothing to do with whether IDisposable is "implemented properly"
Marc Gravell
I'd say leaving a negative comment on my answer, misrepresenting my answer, and creating your own answer which reiterates your disagreement qualifies as an 'aggressive objection.' Any one of those would have been sufficient in and of themselves. I guess we'll just have to disagree on this one too.
Sean Bright
I marked my class sealed and added a finalizer to it that just calls Dispose(), it doesn't matter if my dispose method gets called multiple times it handles state checking already. Then in the middle of my usage I added a Session.Abandon and saw that it indeed was disposing it.
Chris Marisic
A: 

I'd disagree with Sean's answer; firstly, finalizers should not be routinely added to classes, even if they are IDisposable - finalizers should only really be used in classes that represent unmanaged resources. Conversely, a class with a finalizer often is also IDisposable.

Re the question: is Dispose() called - no, it isn't. The object will be garbage collected at some point in the future (indeterminate), but that is about it. A finalizer wouldn't add much here, as any encapsulated objects will also already be eligible for collection (assuming that they aren't referenced elsewhere).

Marc Gravell
A: 

I'd be concerned to have Disposable objects in Session. It will almost certainly create a scalability issue for you. Anything that is Disposable is probably connected to some limited resource, if you have many active sessions you are likely to use up that resource. Secondly I'd expect that many (most?) disposable objects will not work well in a web farm as the resource they are tied to is probably local to a single machine and they won't serialize and then deserialize on another machine in the same state.

ScottS