Graph.as_default has possible wrong return type
Now in tf.net, Graph.as_default returns a value of type Graph. However, in tensorflow (python), it returns a ContextManager, as shown in this code.
What matters is that the returned graph of current as_default API will be disposed and then also disposed the source graph. This happens when we use using(var g = graph.as_default()). The code below could reappear this problem.
var graph = new Graph();
// point 1
using (var g = graph.as_default())
{
// some actions
var op = constant_op.constant("aaaa", TF_DataType.TF_STRING);
// point 2
}
// point 3
We run it under debug mode and watch graph._handle. Then we'll find that in point 1 and 2 it's an meaningful address, but in point 3, it becomes 0x00000000, which means the internal resource of this graph has been cleared.
Users from python often write code like with graph.as_default():, and are easy to treat using grammar as its alternative. #923 mets a problem which throws an error System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.. I met it, too, and I believe it's caused by the incorrect disposing of the return value of Graph.as_default, just like my problem.
The problem is because it's using using explicitly which force GC to dispose the object, even we return ContextManager, it will be disposed prior.
For C# 10 syntax, we can use it as simple as below.
{
using var g = tf.Graph();
// actions
var op = constant_op.constant("aaaa", TF_DataType.TF_STRING);
// point 2
// point3
}
// g will be disposed here