From 5d9e59952bd72bdbf611744016362f890f3c237a Mon Sep 17 00:00:00 2001 From: Radek Zikmund <32671551+rzikm@users.noreply.github.com> Date: Wed, 24 Apr 2024 16:13:16 +0200 Subject: [PATCH] Fix deadlock in TestUtilities.TestEventListener (#101493) --- .../tests/TestUtilities/TestEventListener.cs | 38 ++++++++++++------- 1 file changed, 24 insertions(+), 14 deletions(-) diff --git a/src/libraries/Common/tests/TestUtilities/TestEventListener.cs b/src/libraries/Common/tests/TestUtilities/TestEventListener.cs index bd7b633ba6f822..3c33bdb633e36b 100644 --- a/src/libraries/Common/tests/TestUtilities/TestEventListener.cs +++ b/src/libraries/Common/tests/TestUtilities/TestEventListener.cs @@ -55,34 +55,44 @@ public TestEventListener(ITestOutputHelper output, params string[] sourceNames) public TestEventListener(Action writeFunc, params string[] sourceNames) { + List eventSources = _eventSources; + lock (this) { _writeFunc = writeFunc; _sourceNames = new HashSet(sourceNames); - foreach (EventSource eventSource in _eventSources) + _eventSources = null; + } + + // eventSources were populated in the base ctor and are now owned by this thread, enable them now. + foreach (EventSource eventSource in eventSources) + { + if (_sourceNames.Contains(eventSource.Name)) { - OnEventSourceCreated(eventSource); + EnableEvents(eventSource, EventLevel.LogAlways); } - _eventSources = null; } } protected override void OnEventSourceCreated(EventSource eventSource) { - lock (this) + // We're likely called from base ctor, if so, just save the event source for later initialization. + if (_sourceNames is null) { - // We're called from base ctor, just save the event source for later initialization. - if (_sourceNames is null) + lock (this) { - _eventSources.Add(eventSource); - return; + if (_sourceNames is null) + { + _eventSources.Add(eventSource); + return; + } } + } - // Second pass called from our ctor, allow logging for specified source names. - if (_sourceNames.Contains(eventSource.Name)) - { - EnableEvents(eventSource, EventLevel.LogAlways); - } + // Second pass called after our ctor, allow logging for specified source names. + if (_sourceNames.Contains(eventSource.Name)) + { + EnableEvents(eventSource, EventLevel.LogAlways); } } @@ -102,7 +112,7 @@ protected override void OnEventWritten(EventWrittenEventArgs eventData) } try { - _writeFunc(sb.ToString()); + _writeFunc?.Invoke(sb.ToString()); } catch { } }