开发者

IDisposable - automated check for using construct

开发者 https://www.devze.com 2023-03-10 03:19 出处:网络
Does anybody know of a way to automatically find any variable, where开发者_JAVA百科 the type implements IDisposable but the using construct is not used?

Does anybody know of a way to automatically find any variable, where开发者_JAVA百科 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?


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.


VS 2010 code analyzer's and FxCop? (not sure) Reliability Rules will do a pretty good job on detecting if there exists execution paths in the analyized code where objects implementing IDisposable are going out of scope without calling Dispsoe() (it is overeager and will in many ocasions detect false positives).

This will of course not enforce the using construct as a correctly implemented try-finally block will pass the test (both are obviously equivalent under the hood, so I'm not sure if thats an issue).

EDIT: FX Cop does not support this warning. Its availabe since VS 2005 code analyzer.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号