Skip to content

Race condition during TraceSource Initialization/Refresh #104457

@h3xds1nz

Description

@h3xds1nz

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

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions