@@ -503,15 +503,19 @@ private static void PyDictTryDelItem(BorrowedReference dict, string key)
503
503
private static void MoveClrInstancesOnwershipToPython ( )
504
504
{
505
505
var objs = ManagedType . GetManagedObjects ( ) ;
506
- var copyObjs = objs . ToArray ( ) ;
507
- foreach ( var entry in copyObjs )
506
+ var copyObjs = new KeyValuePair < ManagedType , ManagedType . TrackTypes > [ objs . Count ] ;
508
507
{
509
- ManagedType obj = entry . Key ;
510
- if ( ! objs . ContainsKey ( obj ) )
508
+ int i = 0 ;
509
+ foreach ( var entry in objs )
511
510
{
512
- System . Diagnostics . Debug . Assert ( obj . gcHandle == default ) ;
513
- continue ;
511
+ ManagedType obj = entry . Key ;
512
+ XIncref ( obj . pyHandle ) ;
513
+ copyObjs [ i ++ ] = entry ;
514
514
}
515
+ }
516
+ foreach ( var entry in copyObjs )
517
+ {
518
+ ManagedType obj = entry . Key ;
515
519
if ( entry . Value == ManagedType . TrackTypes . Extension )
516
520
{
517
521
obj . CallTypeClear ( ) ;
@@ -522,8 +526,21 @@ private static void MoveClrInstancesOnwershipToPython()
522
526
PyObject_GC_Track ( obj . pyHandle ) ;
523
527
}
524
528
}
525
- obj . FreeGCHandle ( ) ;
526
- Marshal . WriteIntPtr ( obj . pyHandle , ObjectOffset . magic ( obj . tpHandle ) , IntPtr . Zero ) ;
529
+ }
530
+ foreach ( var entry in copyObjs )
531
+ {
532
+ ManagedType obj = entry . Key ;
533
+ if ( ! objs . ContainsKey ( obj ) )
534
+ {
535
+ System . Diagnostics . Debug . Assert ( obj . gcHandle == default ) ;
536
+ continue ;
537
+ }
538
+ if ( obj . RefCount > 1 )
539
+ {
540
+ obj . FreeGCHandle ( ) ;
541
+ Marshal . WriteIntPtr ( obj . pyHandle , ObjectOffset . magic ( obj . tpHandle ) , IntPtr . Zero ) ;
542
+ }
543
+ XDecref ( obj . pyHandle ) ;
527
544
}
528
545
ManagedType . ClearTrackedObjects ( ) ;
529
546
}
0 commit comments