Skip to content

Commit

Permalink
Fix deadlock in TestUtilities.TestEventListener (#101493)
Browse files Browse the repository at this point in the history
  • Loading branch information
rzikm authored Apr 24, 2024
1 parent 7e29a45 commit 56ee7c5
Showing 1 changed file with 24 additions and 14 deletions.
38 changes: 24 additions & 14 deletions src/libraries/Common/tests/TestUtilities/TestEventListener.cs
Original file line number Diff line number Diff line change
Expand Up @@ -55,34 +55,44 @@ public TestEventListener(ITestOutputHelper output, params string[] sourceNames)

public TestEventListener(Action<string> writeFunc, params string[] sourceNames)
{
List<EventSource> eventSources = _eventSources;

lock (this)
{
_writeFunc = writeFunc;
_sourceNames = new HashSet<string>(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);
}
}

Expand All @@ -102,7 +112,7 @@ protected override void OnEventWritten(EventWrittenEventArgs eventData)
}
try
{
_writeFunc(sb.ToString());
_writeFunc?.Invoke(sb.ToString());
}
catch { }
}
Expand Down

0 comments on commit 56ee7c5

Please sign in to comment.