using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Windows.Forms; using Amphora; namespace Foundations { /// /// Reports the first exception nothing caught, and then ends the program. /// public class DesktopCrashHandler { /// /// The exit code of a run that ended on a crash. /// public const int CrashExitCode = 3; private readonly List> environment; private readonly Action show; private readonly Action exit; private readonly object gate = new object(); private bool hasReported; /// What a report says about the running program, as labeled text, or null. /// Shows a report, and returns once it has been dealt with. /// Ends the program. public DesktopCrashHandler(IEnumerable> environment, Action show, Action exit) { this.environment = environment?.ToList(); this.show = show ?? throw new ArgumentNullException(nameof(show)); this.exit = exit ?? throw new ArgumentNullException(nameof(exit)); } /// /// Shows the report of and ends the program. Safe on any thread. Once a report /// has been taken, a call from the thread showing it returns at once, and one from another thread waits for it. /// public void Report(Exception exception) { // Held while the report shows, since a thread that returns from its unhandled exception takes the process // down, report and all. lock (gate) { // Only the thread holding the lock gets here a second time, from the report's own message loop. if (hasReported) { return; } hasReported = true; try { show(ExceptionReport.WriteCrash(exception, environment)); } finally { exit(); } } } /// /// Has every exception nothing catches show a report and end the program. Does nothing under a debugger, which /// stops where such an exception is thrown. Call it before the program makes its first control. /// public static void Install(Flags flags) { if (Debugger.IsAttached) { return; } var handler = new DesktopCrashHandler( ExceptionReport.DescribeEnvironment(Assembly.GetEntryAssembly(), flags), CrashDialog.ShowOnAnyThread, () => Environment.Exit(CrashExitCode)); // Frames and form events, which WinForms catches itself. Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException); Application.ThreadException += (sender, thrown) => handler.Report(thrown.Exception); // Everything else, which is startup and other threads. AppDomain.CurrentDomain.UnhandledException += (sender, thrown) => handler.Report((Exception)thrown.ExceptionObject); } } }