Skip to content

Commit 23aad53

Browse files
committed
RemoveDisposeScope
1 parent 737c5cb commit 23aad53

File tree

3 files changed

+9
-7
lines changed

3 files changed

+9
-7
lines changed

RELEASENOTES.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ __API Changes__:
1010

1111
__Bug Fixes__:
1212

13+
- Now `DisposeScopes` could be correctly disposed in a wrong order.
1314

1415
# NuGet Version 0.102.4
1516

src/TorchSharp/DisposeScope.cs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,8 @@ public DisposeScope(DisposeScopeManager disposeScopeManager)
2020
{
2121
_disposeScopeManager = disposeScopeManager ?? throw new ArgumentNullException(nameof(disposeScopeManager));
2222
if (disposeScopeManager.DisposeScopeStack.Count > 0) {
23-
OuterScope = disposeScopeManager.DisposeScopeStack.Peek();
23+
OuterScope = disposeScopeManager.DisposeScopeStack[
24+
disposeScopeManager.DisposeScopeStack.Count - 1];
2425
}
2526
}
2627

src/TorchSharp/DisposeScopeManager.cs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ public class DisposeScopeManager
1818
internal ThreadDisposeScopeStatistics StatisticsInstance { get; } = new ThreadDisposeScopeStatistics();
1919

2020
internal static DisposeScopeManager ThreadSingleton => (_threadSingleton ??= new DisposeScopeManager());
21-
internal Stack<DisposeScope> DisposeScopeStack { get; } = new();
21+
internal List<DisposeScope> DisposeScopeStack { get; } = new();
2222

2323
public static ThreadDisposeScopeStatistics Statistics => ThreadSingleton.StatisticsInstance;
2424

@@ -30,7 +30,7 @@ public class DisposeScopeManager
3030
}
3131

3232
StatisticsInstance.CreatedInScopeCount++;
33-
var current = DisposeScopeStack.Peek();
33+
var current = DisposeScopeStack[DisposeScopeStack.Count - 1];
3434
current.Include(disposable);
3535
return current;
3636
}
@@ -42,15 +42,15 @@ internal static DisposeScope NewDisposeScope()
4242

4343
internal void RemoveDisposeScope(DisposeScope disposeScope)
4444
{
45-
Debug.Assert(DisposeScopeStack.Count > 0);
46-
Debug.Assert(DisposeScopeStack.Peek() == disposeScope);
47-
DisposeScopeStack.Pop();
45+
var index = DisposeScopeStack.LastIndexOf(disposeScope);
46+
if (index is not -1)
47+
DisposeScopeStack.RemoveAt(index);
4848
}
4949

5050
private DisposeScope InnerNewDisposeScope()
5151
{
5252
var disposeScope = new DisposeScope(this);
53-
DisposeScopeStack.Push(disposeScope);
53+
DisposeScopeStack.Add(disposeScope);
5454
return disposeScope;
5555
}
5656
}

0 commit comments

Comments
 (0)