diff --git a/src/libraries/System.Private.CoreLib/src/System/AppContext.cs b/src/libraries/System.Private.CoreLib/src/System/AppContext.cs index eef01d3550b0ea..ac2b5b92443276 100644 --- a/src/libraries/System.Private.CoreLib/src/System/AppContext.cs +++ b/src/libraries/System.Private.CoreLib/src/System/AppContext.cs @@ -89,8 +89,6 @@ internal static void OnFirstChanceException(object e) } #endif - internal static event EventHandler? ProcessExit; - internal static void OnProcessExit() { AssemblyLoadContext.OnProcessExit(); @@ -98,8 +96,7 @@ internal static void OnProcessExit() { EventListener.DisposeOnShutdown(); } - - ProcessExit?.Invoke(AppDomain.CurrentDomain, EventArgs.Empty); + AppDomain.OnProcessExit(); } /// diff --git a/src/libraries/System.Private.CoreLib/src/System/AppDomain.cs b/src/libraries/System.Private.CoreLib/src/System/AppDomain.cs index 4359cc41a76040..b07429f409cb60 100644 --- a/src/libraries/System.Private.CoreLib/src/System/AppDomain.cs +++ b/src/libraries/System.Private.CoreLib/src/System/AppDomain.cs @@ -19,7 +19,8 @@ namespace System { public sealed partial class AppDomain : MarshalByRefObject { - private static readonly AppDomain s_domain = new AppDomain(); + private static AppDomain? s_domain; + private IPrincipal? _defaultPrincipal; private PrincipalPolicy _principalPolicy = PrincipalPolicy.NoPrincipal; private Func? s_getWindowsPrincipal; @@ -27,7 +28,19 @@ public sealed partial class AppDomain : MarshalByRefObject private AppDomain() { } - public static AppDomain CurrentDomain => s_domain; + public static AppDomain CurrentDomain + { + get + { + // Create AppDomain instance only once external code asks for it. AppDomain brings lots of unnecessary + // dependencies into minimal trimmed app via ToString method. + if (s_domain == null) + { + Interlocked.CompareExchange(ref s_domain, new AppDomain(), null); + } + return s_domain; + } + } public string BaseDirectory => AppContext.BaseDirectory; @@ -72,10 +85,12 @@ public event EventHandler? FirstChanceException remove { AppContext.FirstChanceException -= value; } } - public event EventHandler? ProcessExit + public event EventHandler? ProcessExit; + + internal static void OnProcessExit() { - add { AppContext.ProcessExit += value; } - remove { AppContext.ProcessExit -= value; } + AppDomain? domain = s_domain; + domain?.ProcessExit?.Invoke(domain, EventArgs.Empty); } public string ApplyPolicy(string assemblyName)