Skip to content

Commit 53c3c4e

Browse files
committed
Fix concurrency issue with registering callback on TestRunCancellationToken (#3958)
1 parent ac7fffb commit 53c3c4e

File tree

1 file changed

+15
-2
lines changed

1 file changed

+15
-2
lines changed

src/Adapter/MSTest.TestAdapter/Execution/TestRunCancellationToken.cs

+15-2
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
// Copyright (c) Microsoft Corporation. All rights reserved.
22
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
33

4+
using System.Collections.Concurrent;
5+
46
namespace Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter;
57

68
/// <summary>
@@ -10,8 +12,9 @@ public class TestRunCancellationToken
1012
{
1113
/// <summary>
1214
/// Callbacks to be invoked when canceled.
15+
/// Needs to be a concurrent collection, see https://github.com/microsoft/testfx/issues/3953.
1316
/// </summary>
14-
private readonly List<Action> _registeredCallbacks = new();
17+
private readonly ConcurrentBag<Action> _registeredCallbacks = new();
1518

1619
/// <summary>
1720
/// Stores whether the test run is canceled or not.
@@ -63,7 +66,17 @@ private set
6366
/// <summary>
6467
/// Unregister the callback method.
6568
/// </summary>
66-
public void Unregister() => _registeredCallbacks.Clear();
69+
public void Unregister()
70+
#if NETCOREAPP || WINDOWS_UWP
71+
=> _registeredCallbacks.Clear();
72+
#else
73+
{
74+
while (!_registeredCallbacks.IsEmpty)
75+
{
76+
_ = _registeredCallbacks.TryTake(out _);
77+
}
78+
}
79+
#endif
6780

6881
internal void ThrowIfCancellationRequested()
6982
{

0 commit comments

Comments
 (0)