Click here to Skip to main content
15,860,943 members
Articles / Desktop Programming / Windows Forms

Finding Undisposed Objects

Rate me:
Please Sign up or sign in to vote.
4.93/5 (105 votes)
13 Aug 2009Ms-PL5 min read 191.2K   2.9K   235   61
An application to find undisposed objects in your .NET application.

Introduction

Who likes to see an unkempt room? A street littered with garbage? A smelly toilet?

Who likes to see objects go undisposed in managed code?

Hopefully, no one.

Non-deterministic garbage collection in .NET makes it your responsibility to dispose objects, and bad things can happen if you don't do that. Besides the cost of finalization, your application could run out of resources and crash if it happens to consume them in a way that doesn't trigger garbage collection.

But, this article isn't about why you need to call Dispose - it assumes you've already seen The Light. This article is about ways to find objects that did not get disposed.

Techniques

The simplest way to find undisposed objects is to add some logging to the finalizer of each disposable type. Running the application through typical scenarios and checking the logs should tell you which types are not being disposed. If you know how to use Windbg and SOS, you can also use the !finalizequeue extension command to view all finalizable types. If the list of finalizable types is small, you can go through your code, looking for missing Dispose calls on instances of those types.

Neither approach works well when there is a huge code base, or if there are third party libraries involved. Enter Undisposed, the subject of this article. It's an application I wrote that uses the CLR profiling API to monitor finalizations and object creations at runtime, and shows you all finalized objects, with stack traces for the respective constructors to help you quickly pinpoint the offending section of code. Here's how the result of the analysis looks:

Image 1

The top panel shows you the number of finalized objects by type, and the bottom panel shows unique stack traces of constructors for the selected type.

How To Use It

Download the application and register Undisposed.dll using:

regsvr32 Undisposed.dll

The DLL requires VC redistributable for VS 2008 SP1, so if registration fails, please install the redistributable from here.

Launch UndisposedViewer.exe:

Image 2

Enter the path of the application to launch, command line arguments (if any), and a log file location. Click on "Automatically find finalizable types" to search for all finalizable types in the application. You can also enter the type names manually. The list of types in the textbox at the bottom will be the ones that will be monitored for finalization. Hitting Go will launch the target application. Put the application through its paces, and once you exit the application, Undisposed LogViewer will launch automatically, showing you the undisposed objects in that specific run of the application.

How It Works

Undisposed.dll

The key component in this application is Undisposed.dll - a COM component that hooks up with the CLR profiling API. In a throwback to old times, the CLR relies on plain old environment variables to know what profiler to load. The "COR_ENABLE_PROFILING" environment variable tells the CLR that profiling is enabled, and it reads the "COR_PROFILER" environment variable to get the CLSID of the component to be loaded as the profiler.

The CLR Profiling API exposes a ICorProfilerCallback2 interface which must be implemented by the COM component. Once loaded, the CLR calls back into the component using methods on that interface. There are a lot of methods there, but these are the ones Undisposed uses.

  • Initialize - Initializes all trackers
  • Shutdown - Shuts down all trackers
  • FinalizeableObjectQueued - Notifies the finalization tracker, which writes out the details to log
  • ObjectAllocated - Notifies the object tracker, which maps objects with the stack trace obtained by walking the stack
  • SurvivingReferences - Notifies the object tracker about objects that survived a garbage collection
  • MovedReferences - Notifies the object tracker about objects that were moved during a garbage collection

The Initialize callback is also used to get an interface pointer to ICorProfilerInfo. The SetEventMask method on that interface is used to tell the CLR the events that the profiler is interested in. For Undisposed, they are:

C++
hr = m_pCorProfilerInfo->SetEventMask(COR_PRF_MONITOR_CLASS_LOADS 
        | COR_PRF_MONITOR_OBJECT_ALLOCATED 
        | COR_PRF_MONITOR_GC 
        | COR_PRF_ENABLE_OBJECT_ALLOCATED
        | COR_PRF_ENABLE_STACK_SNAPSHOT
        )

The COR_PRF_ENABLE_STACK_SNAPSHOT lets the profiler walk the stack using ICorProfilerInfo2::DoStackSnapshot. This is used to get the constructor stack trace for the object the profiler is tracking.

There are lots of other interesting implementation details, enough to warrant a separate article. At a high level though, this is how the code is organized:

Image 3

The Controller forwards calls from the CLR to the appropriate tracker objects. ObjectTracker maintains the list of live objects of all monitored types, along with the stack trace of their constructors. It also does the book keeping after a garbage collection is done. FinalizerRunLogger writes out the object type and the stack trace when it gets notified that an object of one of the monitored types is about to be finalized. TypeTracker, not shown above, maintains a map from the internal data structures to the type names.

UndisposedViewer.exe

The main application merely launches the target application after setting up the environment variables to load Undisposed.dll. It also writes its current state to a config file that is then read by the COM component. This is needed to pass things like the list of types to monitor.

UndisposedLogViewer.exe

The log viewer is launched after the target application exits. There is not much logic in there, it simply reads the log file generated by Undisposed.dll and shows the data grouped by type and stack trace.

Conclusion

The inspiration for writing this application came from this post in the Lounge. Hopefully, it will prove useful to you as well. Feedback and suggestions are welcome.

History

  • 20-07-2009 - Initial version
  • 13-08-2009 - Updated source code and binaries

License

This article, along with any associated source code and files, is licensed under The Microsoft Public License (Ms-PL)


Written By
Software Developer Atmel R&D India Pvt. Ltd.
India India
I'm a 27 yrs old developer working with Atmel R&D India Pvt. Ltd., Chennai. I'm currently working in C# and C++, but I've done some Java programming as well. I was a Microsoft MVP in Visual C# from 2007 to 2009.

You can read My Blog here. I've also done some open source software - please visit my website to know more.

Comments and Discussions

 
QuestionReally wish it worked.. Pin
javieranton2-Sep-16 4:44
javieranton2-Sep-16 4:44 
Bugvery good tool but throw exception. Pin
tornadofay2-Mar-15 9:21
professionaltornadofay2-Mar-15 9:21 
QuestionC sharp version? Pin
i004-Apr-14 7:26
i004-Apr-14 7:26 
GeneralMy vote of 5 Pin
gndnet21-Jul-12 2:51
gndnet21-Jul-12 2:51 
GeneralMy vote of 5 Pin
gndnet19-Jul-12 21:42
gndnet19-Jul-12 21:42 
GeneralMy vote of 5 Pin
thatraja3-Dec-10 22:57
professionalthatraja3-Dec-10 22:57 
QuestionWhy log file? Pin
Vitaly Tomilov3-May-10 8:29
Vitaly Tomilov3-May-10 8:29 
AnswerRe: Why log file? Pin
S. Senthil Kumar3-May-10 9:23
S. Senthil Kumar3-May-10 9:23 
GeneralRe: Why log file? Pin
Vitaly Tomilov3-May-10 9:27
Vitaly Tomilov3-May-10 9:27 
Question[My vote of 1] What is the motivation for doing this? Pin
wishay14-Apr-10 11:57
wishay14-Apr-10 11:57 
AnswerRe: [My vote of 1] What is the motivation for doing this? Pin
S. Senthil Kumar14-Apr-10 17:35
S. Senthil Kumar14-Apr-10 17:35 
GeneralRe: [My vote of 1] What is the motivation for doing this? Pin
wishay14-Apr-10 21:56
wishay14-Apr-10 21:56 
QuestionFound lots of objects. Now what? Pin
Paul Meems25-Aug-09 1:13
Paul Meems25-Aug-09 1:13 
AnswerRe: Found lots of objects. Now what? Pin
S. Senthil Kumar25-Aug-09 1:18
S. Senthil Kumar25-Aug-09 1:18 
Generalvery good - my vote of 4! Pin
Pratik.Patel23-Aug-09 17:42
Pratik.Patel23-Aug-09 17:42 
Questionhow to test it? Pin
elvis_pan21-Aug-09 22:59
elvis_pan21-Aug-09 22:59 
AnswerRe: how to test it? Pin
S. Senthil Kumar22-Aug-09 1:13
S. Senthil Kumar22-Aug-09 1:13 
GeneralCLR Profiler Pin
zubairy21-Aug-09 18:20
zubairy21-Aug-09 18:20 
GeneralRe: CLR Profiler Pin
S. Senthil Kumar22-Aug-09 7:28
S. Senthil Kumar22-Aug-09 7:28 
QuestionStill cannot find log file Pin
hat_master18-Aug-09 10:53
hat_master18-Aug-09 10:53 
AnswerRe: Still cannot find log file Pin
S. Senthil Kumar18-Aug-09 17:25
S. Senthil Kumar18-Aug-09 17:25 
QuestionWhat is Leaky.exe? Pin
BOWLINGBALL18-Aug-09 2:14
BOWLINGBALL18-Aug-09 2:14 
AnswerRe: What is Leaky.exe? Pin
S. Senthil Kumar18-Aug-09 2:38
S. Senthil Kumar18-Aug-09 2:38 
QuestionError: Could not find file : and Pin
liquidfirexyz12-Aug-09 8:56
liquidfirexyz12-Aug-09 8:56 
AnswerRe: Error: Could not find file : and Pin
S. Senthil Kumar12-Aug-09 21:01
S. Senthil Kumar12-Aug-09 21:01 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.