diff --git a/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/TraceSource.cs b/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/TraceSource.cs index c3b52b4f12ce06..87cea31a8e9350 100644 --- a/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/TraceSource.cs +++ b/src/libraries/System.Diagnostics.TraceSource/src/System/Diagnostics/TraceSource.cs @@ -504,12 +504,35 @@ public StringDictionary Attributes internal void OnInitializing(InitializingTraceSourceEventArgs e) { Initializing?.Invoke(this, e); - TraceUtils.VerifyAttributes(Attributes, GetSupportedAttributes(), this); - foreach (TraceListener listener in Listeners) + if (TraceInternal.UseGlobalLock) + { + // we lock on the same object that Trace does because we're writing to the same Listeners. + lock (TraceInternal.critSec) + { + foreach (TraceListener listener in Listeners) + { + TraceUtils.VerifyAttributes(listener.Attributes, listener.GetSupportedAttributes(), this); + } + } + } + else { - TraceUtils.VerifyAttributes(listener.Attributes, listener.GetSupportedAttributes(), this); + foreach (TraceListener listener in Listeners) + { + if (!listener!.IsThreadSafe) + { + lock (listener) + { + TraceUtils.VerifyAttributes(listener.Attributes, listener.GetSupportedAttributes(), this); + } + } + else + { + TraceUtils.VerifyAttributes(listener.Attributes, listener.GetSupportedAttributes(), this); + } + } } }