Search code examples
c#disposecorrectness

How much work in the Dispose method?


How much work should be done in a Dispose method? In constructors I've always taken the stance that you should only do what is absolutely necessary to instantiate the object. This being the case I've also always taken the approach that you should ONLY be cleaning up open resources when disposing. Closing files, freeing memory, disposing of child disposable object, etc. You shouldn't be doing lengthy processes like touching files, accessing databases and such in the Dispose method.

Am I wrong? Are those action's OK as long as you are handling any possible exceptions so they don't bubble out of the method? I just don't think doing a lot in Dispose is a good idea. I would like to know what the community thinks.


Solution

  • Am I wrong?

    No, you are right. In general the Dispose method is used to clean the unmanaged resources that your class might have allocated.

    But that's difficult to generalize. There are cases where the Dispose method is simply used to ensure that some operation executes. For example in ASP.NET MVC there's the Html.BeginForm helper which is used like that:

    using (Html.BeginForm())
    {
    
    }
    

    and all that the Dispose method does is render a closing </form> tag. So as you can see people could be creative with the pattern and it is very difficult to draw conclusions without a specific scenario.

    But in the most common situations it's used to release unmanaged resources.