From 53c3c4ec895e3df9b60659ebf60622e0078e7cfb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Mon, 21 Oct 2024 14:26:51 +0200 Subject: [PATCH] Fix concurrency issue with registering callback on TestRunCancellationToken (#3958) --- .../Execution/TestRunCancellationToken.cs | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/src/Adapter/MSTest.TestAdapter/Execution/TestRunCancellationToken.cs b/src/Adapter/MSTest.TestAdapter/Execution/TestRunCancellationToken.cs index eebf71446c..7faaabe606 100644 --- a/src/Adapter/MSTest.TestAdapter/Execution/TestRunCancellationToken.cs +++ b/src/Adapter/MSTest.TestAdapter/Execution/TestRunCancellationToken.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using System.Collections.Concurrent; + namespace Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter; /// @@ -10,8 +12,9 @@ public class TestRunCancellationToken { /// /// Callbacks to be invoked when canceled. + /// Needs to be a concurrent collection, see https://github.com/microsoft/testfx/issues/3953. /// - private readonly List _registeredCallbacks = new(); + private readonly ConcurrentBag _registeredCallbacks = new(); /// /// Stores whether the test run is canceled or not. @@ -63,7 +66,17 @@ private set /// /// Unregister the callback method. /// - public void Unregister() => _registeredCallbacks.Clear(); + public void Unregister() +#if NETCOREAPP || WINDOWS_UWP + => _registeredCallbacks.Clear(); +#else + { + while (!_registeredCallbacks.IsEmpty) + { + _ = _registeredCallbacks.TryTake(out _); + } + } +#endif internal void ThrowIfCancellationRequested() {