dotnet / runtime

.NET is a cross-platform runtime for cloud, mobile, desktop, and IoT apps.
https://docs.microsoft.com/dotnet/core/
MIT License
14.84k stars 4.62k forks source link

Race condition during TraceSource Initialization/Refresh #104457

Closed h3xds1nz closed 2 weeks ago

h3xds1nz commented 1 month ago

Description

TraceSource is documented to be a thread-safe, however when you call System.Diagnostics.Trace.Refresh() during TraceSource initialization from a different thread, you have a high chance of receiving either InvalidOperationException or NullReferenceException from the OnInitializing method during the enumeration of Listeners.

There seem to be a lack of synchronization on the collection, this seem to have been introduced in #73087

Reproduction Steps

You can find a demo repository on Github - here.

Expected behavior

I can call System.Diagnostics.Trace.Refresh() safely from a different thread during underlying TraceSource initialization without the risk of crashing.

Actual behavior

A high chance of receiving either InvalidOperationException or NullReferenceException from the OnInitializing method during the enumeration of Listeners as the collection might have been modified or initialized from a different thread.

Regression?

Since #73087, previous .NET version (6) didn't suffer from this issue.

Known Workarounds

In case of WPF, wait some time before invoking a Refresh.

Configuration

.NET 8.0.6 x64 Win10

dotnet-policy-service[bot] commented 1 month ago

Tagging subscribers to this area: @tarekgh, @tommcdon, @pjanotti See info in area-owners.md if you want to be subscribed.

tommcdon commented 1 month ago

@noahfalk @hoyosjs

ericstj commented 1 month ago

@steveharter can you have a look at this?