IDisposable - automated check for using construct

时光总嘲笑我的痴心妄想 提交于 2020-01-04 01:19:26

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/6213901/idisposable-automated-check-for-using-construct

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!