Chained calls may cause memory leaks?

64 Views Asked by At

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.

1

There are 1 best solutions below

1
Guru Stron On
This kind of memory leak seems to be relatively easy to happen.

Yes, it does, and yes, if you have a IDisposable object which controls some unmanaged resources and you will not call Dispose on it (manually or via using) you will get a memory leak unless you have a finalizer defined:

Finalizers (historically referred to as destructors) are used to perform any necessary final clean-up when a class instance is being collected by the garbage collector.

Hence using some fluent API-like calls on such code is dangerous. For example in the following code:

var result = CreateSomeInstWithUnmanagedResource()
    .TransformTheInstanceWithoutCapture();

If TransformTheInstanceWithoutCapture does not dispose the incoming instance with unmanaged resources created by CreateSomeInstWithUnmanagedResource then 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: