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

System.ObjectDisposedException in Tensorflow dll

Open DoraAHsu opened this issue 3 years ago • 5 comments

I got some error when my application was closed. The compiler return as follows: 未處理的例外狀況: System.ObjectDisposedException: 無法存取已處置的物件。 物件名稱: 'ThreadLocal 物件已被處置。'。 於 System.Threading.ThreadLocal`1.GetValueSlow() 於 Tensorflow.Variables.EagerResourceDeleter.DisposeUnmanagedResources(IntPtr handle) 於 Tensorflow.DisposableObject.Dispose(Boolean disposing) 於 Tensorflow.DisposableObject.Finalize()

How to fix this error?

DoraAHsu avatar Feb 14 '23 09:02 DoraAHsu

It seems to be caused by double dispose. Could you please provide a minimal example that can reproduce this error?

SanftMonster avatar Feb 15 '23 12:02 SanftMonster

Is it possible that the TensorFlow object will auto-delete by itself? Actually, I just call the third-party Lib(It call Tensorflow.net). When the training model flow was finished, then I close the application, then error happened!

DoraAHsu avatar Feb 16 '23 08:02 DoraAHsu

Maybe the Tensor A is the handle of the Tensor B. Then Tensor B still try to dispose Tensor A while Tensor A has already been disposed. However, though I'm more than happy to help you, I can't reproduce it without any code.

Would you mind providing a code that can reproduce the error? You can modify your model definition to protect your privacy. Thank you!

SanftMonster avatar Feb 16 '23 08:02 SanftMonster

I just call the third-party Lib

Do you mind if tell the name of the third-party lib which calls tensorflow.net?

Oceania2018 avatar Mar 05 '23 03:03 Oceania2018

I found this same bug.

EagerResourceDeleters DisposeUnmanagedResources uses tf.Context which is another finalizable type - ThreadLocalStorage. That type might be finalized before EagerResourceDeleter and if so it will cause a crash the same as was hit in https://github.com/SciSharp/TensorFlow.NET/issues/912 with Session.

https://github.com/SciSharp/TensorFlow.NET/blob/6ce6066551ce80202119a121a05b006aadd9ef37/src/TensorFlowNET.Core/Variables/EagerResourceDeleter.cs#L24-L26

An object has to be super careful about what it puts in a finalizer. The only guarantee is that it can access data in base classes and itself. Value types are safe. Any reference type may not be safe if it too is finalizable - it may be finalized before the current type.

Fix here would be to either remove the DisposeUnmanagedResources or have the type capture whatever state it needs as a local that's not a finalizable object.

ericstj avatar Jul 11 '25 21:07 ericstj