Call library in new AppDomain to prevent exceptions from propagating

90 views Asked by At

I'm using a flaky third party library that throws exceptions on internal threads that I cannot catch. I'm trying to sandbox the library into a separate AppDomain so that the exceptions don't bring my application down and so I can implement retry logic.

This is what I've got so far, however it seems to execute on the default AppDomain. The exception crashes the application.

var ad = AppDomain.CreateDomain("Sandbox");
ad.UnhandledException += (o, e) =>
{
    Console.WriteLine("Who Cares");
};

dynamic lib = ad.CreateInstance("TestLibrary, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", "TestLibrary.TestLibrary").Unwrap();
lib.DoWork();
1

There are 1 answers

2
Przemysław Ładyński On

Try this approach:

var ad = AppDomain.CreateDomain("Sandbox");
ad.UnhandledException += (o, e) =>
{
    Console.WriteLine("Who Cares");
};
ad.Load("TestLibrary.TestLibrary");
ad.DoCallBack(() =>
{
     TestLibrary lib = new TestLibrary();
     lib.DoWork();
});

Because when you unwrap that type it gets loaded in the main app domain as well. Using this approach all will stay in other AppDomain. Next you can get back to your main app domain some simple marshalable result.