1

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();
ConditionRacer
  • 4,418
  • 6
  • 45
  • 67
  • Oh, I was wondering if you had managed to fix your problem. I added an edit to the answer I posted to your other question. I was hoping that would help you. Nothing worse than inheriting a (badly written) third party library over which you have no control. ([The other related question if anyone is interested](http://stackoverflow.com/questions/30848850/any-way-to-catch-an-exception-occurring-on-a-thread-i-dont-own)) – sstan Jun 16 '15 at 17:34
  • @sstan Thanks, I saw your answer. I'm trying to figure out how to offload the library onto a new AppDomain, not the default domain. – ConditionRacer Jun 16 '15 at 17:45
  • The odds that this class derives from MarshalByRefObject are zero. If it works then it is [Serializable]. You have to run *all* of the code in the appdomain, yours as well. – Hans Passant Jun 16 '15 at 17:45
  • @HansPassant So am I stuck running this in a separate process? – ConditionRacer Jun 16 '15 at 17:46
  • I am wondering why you can't use the events for unhandled exceptions to prevent to other library from crashing your app? Is it throwing exceptions that can't be handled like `StackOverflowException`? – Daniel Hilgarth Jun 16 '15 at 18:04
  • @Daniel Hilgarth It's throwing exceptions on threads that I don't have access to. See the link sstan posted for more info. – ConditionRacer Jun 16 '15 at 19:39

1 Answers1

3

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.