Skip to content

Commit

Permalink
Remove dependency on AppDomain from a hello world app
Browse files Browse the repository at this point in the history
Saves 4% in size on a hello world.

A hello world app will bring the `AppDomain` type with it. `AppDomain`'s `ToString` is quite expensive for what it does.

Maybe this can be done cleaner, suggestions welcome.
  • Loading branch information
MichalStrehovsky committed Dec 6, 2023
1 parent 1aae18a commit 047553d
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 4 deletions.
23 changes: 21 additions & 2 deletions src/libraries/System.Private.CoreLib/src/System/AppContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,26 @@ internal static void OnFirstChanceException(object e)
}
#endif

internal static event EventHandler? ProcessExit;
private static event EventHandler? s_processExit;

// We invoke process exit callback through an indirection.
// Most apps will not install a callback in the first place.
// To invoke the callback, we need to pass the current AppDomain.
// AppDomain brings lots of unnecessary dependencies into trimmed apps.
// The indirection is set up when the callback is installed so that
// only apps that install a callback have AppDomain in the closure.
private static Action s_invokeProcessExitCallback;

internal static void AddProcessExitCallback(EventHandler eventHandler)
{
s_processExit += eventHandler;
s_invokeProcessExitCallback ??= () => s_processExit?.Invoke(AppDomain.CurrentDomain, EventArgs.Empty);
}

internal static void RemoveProcessExitCallback(EventHandler eventHandler)
{
s_processExit -= eventHandler;
}

internal static void OnProcessExit()
{
Expand All @@ -99,7 +118,7 @@ internal static void OnProcessExit()
EventListener.DisposeOnShutdown();
}

ProcessExit?.Invoke(AppDomain.CurrentDomain, EventArgs.Empty);
s_invokeProcessExitCallback();
}

/// <summary>
Expand Down
4 changes: 2 additions & 2 deletions src/libraries/System.Private.CoreLib/src/System/AppDomain.cs
Original file line number Diff line number Diff line change
Expand Up @@ -74,8 +74,8 @@ public event EventHandler<FirstChanceExceptionEventArgs>? FirstChanceException

public event EventHandler? ProcessExit
{
add { AppContext.ProcessExit += value; }
remove { AppContext.ProcessExit -= value; }
add { AppContext.AddProcessExitCallback(value); }
remove { AppContext.RemoveProcessExitCallback(value); }
}

public string ApplyPolicy(string assemblyName)
Expand Down

0 comments on commit 047553d

Please sign in to comment.