Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IDisposable - automated check for using construct

Does anybody know of a way to automatically find any variable, where the type implements IDisposable but the using construct is not used?

ie. a way to check for potentially unreleased unmanaged resources?

Also, is it possible to see the number and types of resource held by a running application?

like image 473
Paul Creasey Avatar asked May 10 '26 02:05

Paul Creasey


1 Answers

There's a code analysis rule for this:

http://msdn.microsoft.com/en-us/library/ms182289%28VS.100%29.aspx

This can be run from VS 2010 Premium or Ultimate or separately with FxCop:

http://www.microsoft.com/downloads/en/details.aspx?FamilyID=917023f6-d5b7-41bb-bbc0-411a7d66cf3c

Another thing I've seen done is to capture a stack trace when an IDisposable object is constructed and then if the finalize is hit (meaning Dispose() was not called) log an error with the constructed stack trace. This is expensive so you may only want to do it in development, or only start collecting stack traces the second time your app runs into this problem (if you run into it once, you're most likely going to run into it many times within a single app execution). This method works for IDisposable instances that are longer lived (not just local variables). Of course it also only works for custom IDisposable objects since it requires custom code in the constructor/dispose/finalizer.

like image 132
Samuel Neff Avatar answered May 12 '26 18:05

Samuel Neff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!