Catch all exceptions from Exit shutdown #12518
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Fixes #7367 in 2.2.
If we fail to log to console due to an invalid handle, catch the exception no matter what.
Writing a test for this is really hard as I would need to muck with Console.* to make it throw.
Impact
This bug is to fix an issue with hosting aspnetcore in IIS In-process. On process shutdown, hosting tries to log to Console OnProcessExit. When hosting inprocess, once the main thread returns, we restore the original handle which the app originally had, making the old handle invalid. However, OnProcessExit runs after the main thread returns, which causes a race condition between the handle being invalid and the log to console. As this is on a background thread, it crashes the application.
Workaround
There are no work arounds. Once an event is added to AppDomain.ProcessExit, I don't believe it can be removed without the original event which is internal.
Risk
Very low. This only affects one call to Console.WriteLine and a cts.Cancel to catch all exceptions on process exit rather than only catching around the cts for an ODE.
cc @NickCraver