8000 delay nulling GC handles of reflected instances until the last moment… · pythonnet/pythonnet@c2e207a · GitHub
[go: up one dir, main page]

Skip to content

Commit c2e207a

Browse files
committed
delay nulling GC handles of reflected instances until the last moment to allow them to be garbage collected
1 parent 932fce2 commit c2e207a

File tree

1 file changed

+9
-30
lines changed

1 file changed

+9
-30
lines changed

src/runtime/runtime.cs

Lines changed: 9 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -312,7 +312,7 @@ internal static void Shutdown(ShutdownMode mode)
312312
ClearClrModules();
313313
RemoveClrRootModule();
314314

315-
MoveClrInstancesOnwershipToPython();
315+
NullGCHandles(ExtensionType.loadedExtensions);
316316
ClassManager.RemoveClasses();
317317
TypeManager.RemoveTypes();
318318

@@ -382,7 +382,13 @@ static bool TryCollectingGarbage()
382382
pyCollected += Finalizer.Instance.DisposeAll();
383383
}
384384
if (Volatile.Read(ref _collected) == 0 && pyCollected == 0)
385+
{
385386
return true;
387+
}
388+
else
389+
{
390+
NullGCHandles(CLRObject.reflectedObjects);
391+
}
386392
}
387393
return false;
388394
}
@@ -521,40 +527,13 @@ private static void PyDictTryDelItem(BorrowedReference dict, string key)
521527
PyErr_Clear();
522528
}
523529

524-
private static void MoveClrInstancesOnwershipToPython()
530+
private static void NullGCHandles(IEnumerable<IntPtr> objects)
525531
{
526-
foreach (IntPtr objWithGcHandle in ExtensionType.loadedExtensions
527-
.Concat(CLRObject.reflectedObjects)
528-
.ToArray()
529-
)
532+
foreach (IntPtr objWithGcHandle in objects.ToArray())
530533
{
531534
var @ref = new BorrowedReference(objWithGcHandle);
532535
ManagedType.TryFreeGCHandle(@ref);
533536
}
534-
535-
//foreach (IntPtr extensionAddr in ExtensionType.loadedExtensions.ToArray())
536-
//{
537-
// var @ref = new BorrowedReference(extensionAddr);
538-
// var type = PyObject_TYPE(@ref);
539-
// //ManagedType.CallTypeClear(@ref, type);
540-
// // obj's tp_type will degenerate to a pure Python type after TypeManager.RemoveTypes(),
541-
// // thus just be safe to give it back to GC chain.
542-
// if (PyVersion >= new Version(3, 9))
543-
// {
544-
// if (!PyObject_GC_IsTracked(@ref))
545-
// {
546-
// PyObject_GC_Track(@ref);
547-
// }
548-
// }
549-
// else
550-
// {
551-
// // in older CPython versions it is safe to call UnTrack any number of time
552-
// // but Track can only be called on something previously untracked
553-
// PyObject_GC_UnTrack(@ref);
554-
// PyObject_GC_Track(@ref);
555-
// }
556-
557-
//}
558537
}
559538

560539
#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable.

0 commit comments

Comments
 (0)
0