In a chain call, there are intermediate products. If there is an intermediate product that inherits from IDisposable, then usually we should use using to make it automatically released. But I ignored this in the chain call and only used one using to release the resource object I ultimately needed. So will this cause a memory leak?
According to my actual test: divide the chain call into multiple lines for execution, and use using to modify all resource objects in it (not just the last one). Comparing the memory usage before and after shows that there is indeed a memory leak. I would like to ask if anyone has encountered this situation. This kind of memory leak seems to be relatively easy to happen.
This kind of memory leak seems to be relatively easy to happen.
Yes, it does, and yes, if you have a
IDisposableobject which controls some unmanaged resources and you will not callDisposeon it (manually or viausing) you will get a memory leak unless you have a finalizer defined:Hence using some fluent API-like calls on such code is dangerous. For example in the following code:
If
TransformTheInstanceWithoutCapturedoes not dispose the incoming instance with unmanaged resources created byCreateSomeInstWithUnmanagedResourcethen the resources will not be disposed.Though relying on finalizers is not recommended for multiple reasons, for example due to the non-deterministic invocation (you don't know when GC will run) start and prolonged lifetime of the finalized object.
See also: