Tuesday, July 15, 2003

Resource Management in .NET

The resource management strategy in not well thought out in the .NET framework. Take the following two lines of code:

Brush b = Brushes.White;
Font f = SystemInformation.MenuFont;

You are not supposed to dispose the first brush as the Brushes collection is giving you a cached copy. But the font returned by the MenuFont property is a newly created one that you need to dispose.

Is this obvious from the code? No. Is it stated somewhere in the docs? No.

The best resource management strategy would be for the CLR to introduce an additional breed of reference that would do automatic reference counting, akin to a C++ reference counting smart pointer.

Since that doesn't look like it's going to happen, a reasonable approach would be to introduce [Borrows] and [Owns] attributes and to add them to function parameters and return values. That could be used to produce documentation automatically and to produce tools that hunt for leaks.

   3:43 PM

Content of this site is © Dejan Jelovic. All rights reserved.