Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I gracefully handle faulty AppDomains?

Tags:

c#

appdomain

Is this code snippet poorly designed? Originally, there was only one AppDomain.Unload, in the finally block. This had the unfortuanate side effect that other threads could keep running in the AppDomain while UnhandledException was running, which among other things uses user input and is hence very slow on a computing scale (average real runtime might be >1min), potentially throwing other exceptions and generally causing more problems. I'm stuck on thinking of a 'better' way of doing this, so, I submit this to SO. Lend me your minds.

Note: I just realised there's synchronisation issues here too. Yes, I know what they are, lets stay focused.

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]
}
like image 461
Matthew Scharley Avatar asked Dec 30 '25 15:12

Matthew Scharley


1 Answers

I would strive for no duplication. And imo you could make this work with only cleaning up the appdomain in your finally block, as you did initially. The idea being that if an unhandled exception occurs, place it in a variable and process it after shutting down the appdomain.

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

if (unhandledException != null)
    UnhandledException(this, new UnhandledExceptionEventArgs(unhandledException, false));
like image 78
Peter Lillevold Avatar answered Jan 01 '26 04:01

Peter Lillevold



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!