Calling Dispose() vs when an object goes out scope/method finishes

前端 未结 6 723
情深已故
情深已故 2020-12-30 05:58

I have a method, which has a try/catch/finaly block inside. Within the try block, I declare SqlDataReader as follows:

SqlDataReader         


        
6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-30 06:09

    I agree with all of the above. You should make sure you call Dispose() yourself, and the easiest way to to this is with the using statement (you can also do this yourself in the finally block - this is more verbose, but sometimes necessary). If you don't do this you can find your application leaking unmanaged resources such as handles, or even unmanaged memory, especially if somewhere underneath all of this some COM components are being used, or calls are being made into the Win32 API. This can obviously lead to performance and stability problems, as well as excessive resource usage.

    Just because objects that implement IDisposable "should" implement a finaliser that calls their Dispose(bool disposing) method to free unmanaged resources, is no guarantee that this will happen, so you definitely should not rely on it. See, for example, http://msdn.microsoft.com/en-us/library/b1yfkh5e%28VS.71%29.aspx for more information on this point.

    Also, something else to bear in mind, is that if your type has members that are disposable, your type should either implement IDisposable (unless the lifecycle of those members is managed by another type, which obviously might get messy), or, if you only use such members in one method, or to implement one particular piece of functionality, you should consider making them local variables/parameters in the methods that use them.

提交回复
热议问题