Skip to content

Commit 605ab06

Browse files
add DefaultGraphStack
1 parent 25e35d1 commit 605ab06

File tree

1 file changed

+33
-1
lines changed

1 file changed

+33
-1
lines changed

Diff for: TensorFlowSharp/Tensorflow.cs

+33-1
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,36 @@ internal static void CheckSize ()
108108
}
109109
}
110110

111+
internal class DefaultGraphStack
112+
{
113+
[ThreadStatic]
114+
private static IList<TFGraph> stack;
115+
private static object lockObj = new object();
116+
117+
internal TFGraph Instance => stack.Last();
118+
119+
internal static void SetGraph(TFGraph graph)
120+
{
121+
if (stack == null)
122+
{
123+
lock (lockObj)
124+
{
125+
if (stack == null)
126+
{
127+
stack = new List<TFGraph>();
128+
}
129+
}
130+
}
131+
132+
stack.Add(graph);
133+
}
134+
135+
internal static void RemoveGraph(TFGraph graph)
136+
{
137+
stack.Remove(graph);
138+
}
139+
}
140+
111141
/// <summary>
112142
/// Base class for many TensorFlow data types that provides a common idiom to dispose and
113143
/// release resources associated with the native data types. Generally, you do not need to use this.
@@ -473,19 +503,21 @@ public partial class TFGraph : TFDisposable
473503
/// <summary>
474504
/// Initializes a new instance of the <see cref="T:TensorFlow.TFGraph"/> class.
475505
/// </summary>
476-
public TFGraph () : base (TF_NewGraph ())
506+
public TFGraph () : this (TF_NewGraph ())
477507
{
478508
}
479509

480510
internal TFGraph (IntPtr handle) : base (handle)
481511
{
512+
DefaultGraphStack.SetGraph(this);
482513
}
483514

484515
// extern void TF_DeleteGraph (TF_Graph *);
485516
[DllImport (NativeBinding.TensorFlowLibrary)]
486517
static extern unsafe void TF_DeleteGraph (TF_Graph graph);
487518
internal override void NativeDispose (IntPtr handle)
488519
{
520+
DefaultGraphStack.RemoveGraph(this);
489521
TF_DeleteGraph (handle);
490522
}
491523

0 commit comments

Comments
 (0)