How should I handle failed AppDomains correctly?

Is this piece of code poorly designed? Initially, there was only one in the finally block AppDomain.Unload. This had an unpleasant side effect that other threads could continue to work in the AppDomain while it was running UnhandledException, which, among other things, uses user input and is therefore very slow on a computational scale (average real time may be> 1 minute), potentially throwing others exceptions and tend to cause more problems. I am stuck with the “best” way to do this, so I submit to this SO. Lend me your thoughts.

Note. I just realized that this is a synchronization problem. Yes, I know what it is, let's focus.

mainApp = AppDomain.CreateDomain(ChildAppDomain, null, AppDomain.CurrentDomain.SetupInformation);
try
{
    mainApp.ExecuteAssembly(Assembly.GetEntryAssembly().Location);
    finished = true;
}
catch (Exception ex)
{
    AppDomain.Unload(mainApp);
    mainApp = null;
    UnhandledException(this, new UnhandledExceptionEventArgs(ex, false));
}
finally
{
    if (mainApp != null)
    {
        AppDomain.Unload(mainApp);
        mainApp = null;
    }
}

// ...

void UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
    if (mainApp != null)
    {
        AppDomain.Unload(mainApp);
        mainApp = null;
    }
    // [snip]
}
+3
source share
1 answer

I would not strive for duplication. Imo you can do this work only by clearing the appdomain in your finally block, as you did at the beginning. The idea is that if an unhandled exception occurs, put it in a variable and process it after you close the application.

Exception unhandledException = null;
try
{
    ...
}
catch (Exception ex)
{
    unhandledException = ex;
}
finally
{
    CleanupAppDomain(mainApp);
}

if (unhandledException != null)
    UnhandledException(this, new UnhandledExceptionEventArgs(unhandledException, false));
+2
source

Source: https://habr.com/ru/post/1720436/


All Articles