Will an IDisposable memory leak if you don’t use a using statement?
And if so, can someone provide a memory leak example if its not much code?
Will an IDisposable memory leak if you don’t use a using statement? And if
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
A correctly-written program which creates an instance of a type that implements
IDisposable, and which is not specifically known to be capable of adequately cleaning up after itself when abandoned, must ensure thatDisposeis called on that instance before abandoning it. Any program which fails to callDisposeon a type which is not specifically known to be fine without it is broken.Although it would be nice if automatic finalization could take care of everything, it’s a pretty crummy cleanup mechanism. It provides no guarantees with regard to sequencing, threading context, timeliness, or certainty of completion (when using deterministic cleanup, one can make reasonably certain that a program won’t appear to complete normally if cleanup fails; when using finalization, a program may appear to complete normally without even attempting to clean up an object).
Microsoft may once have intended that every
IDisposableclass should be able to adequately clean up after itself if abandoned, but that is simply not practical. In many cases, for a class to attempt to clean up after itself if abandoned would add a massive amount of complexity, and would simply turn a broken program that would have obvious problems that are easy to track down, into a broken program that usually works except when the timing of the finalizer thread relative to some other thread causes things to fail in some unexpected and non-reproducible fashion.There are some types which, despite implementing
IDisposable, are unconditionally safe to abandon, and there are some others which may be safely abandoned in certain circumstances. It is fine to abandon such types in situations where disposing them would be difficult (e.g. because references are held by multiple objects that are manipulated by various threads, and there’s no nice way by which any particular object can know it when it holds the last surviving reference), provided that one documents one’s reasons for believing that such action is safe and appropriate. Such behavior is not appropriate, however, in cases where one has acceptedIDisposableobjects of unknown lineage.