From 0ab744486366c034872aff00b8578b3d4be5c732 Mon Sep 17 00:00:00 2001 From: Stephen Toub Date: Thu, 21 Jul 2022 12:50:28 -0400 Subject: [PATCH] Avoid AsyncLocal read in Activity.set_Current when CurrentChanged isn't handled --- .../System/Diagnostics/Activity.Current.net46.cs | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/Activity.Current.net46.cs b/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/Activity.Current.net46.cs index 48e0617cf6f21f..9070bd44a16ca2 100644 --- a/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/Activity.Current.net46.cs +++ b/src/libraries/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/Activity.Current.net46.cs @@ -27,9 +27,17 @@ public static Activity? Current private static void SetCurrent(Activity? activity) { - Activity? previous = s_current.Value; - s_current.Value = activity; - CurrentChanged?.Invoke(null, new ActivityChangedEventArgs(previous, activity)); + EventHandler? handler = CurrentChanged; + if (handler is null) + { + s_current.Value = activity; + } + else + { + Activity? previous = s_current.Value; + s_current.Value = activity; + handler.Invoke(null, new ActivityChangedEventArgs(previous, activity)); + } } } }