TensorFlow.NET icon indicating copy to clipboard operation
TensorFlow.NET copied to clipboard

How to deterministically release TF objects

Open ericstj opened this issue 5 months ago • 1 comments

Description

When updating to the latest TF.NET I noticed that Dispose methods were removed from types.

This seems to be done in https://github.com/SciSharp/TensorFlow.NET/commit/e5dfe90e9b5107fe6de7f4e73c54feee1c94f4ff#diff-fa5a105168638b6355c038d3eb3749d77f6e7c38c91bf7ec623b26cac68a8d1e

While using SafeHandles is good, that doesn't eliminate the need for Dispose. Objects which contain other objects with a Dispose method, should themselves expose a Dispose method, even if they don't have native resources to dispose. This helps callers get a deterministic Dispose rather than waiting for GC / Finalizers to run.

See https://learn.microsoft.com/en-us/dotnet/standard/design-guidelines/dispose-pattern

✓ DO implement the Basic Dispose Pattern on types containing instances of disposable types. See the Basic Dispose Pattern section for details on the basic pattern.

If a type is responsible for the lifetime of other disposable objects, developers need a way to dispose of them, too. Using the container’s Dispose method is a convenient way to make this possible.

ericstj avatar Jul 09 '25 16:07 ericstj

The removal of Dispose methods was also a binary breaking change. I was able to workaround that by casting these objects to their SafeHandle types then calling Dispose on those, but I wanted to pose the above question as a better reason to preserve the existing behavior -- since presumably TF.NET doesn't have a binary compatibility promise.

ericstj avatar Jul 09 '25 18:07 ericstj