0

I'm trying to figure out how to use AppDomains.

The Need:

I have a single process web application which dynamically loads dlls and invokes it using reflection.

I want to ensure that a crash in a loaded dll does not crash the process, in addition to creating a seperation between "external" code and my base code.

So I have this "isloated" class:

public sealed class Isolated<T> : IDisposable where T : MarshalByRefObject
{
    private AppDomain _domain;
    private T _value;

    public Isolated()
    {
        _domain = AppDomain.CreateDomain("Isolated:" + Guid.NewGuid(),
           null, AppDomain.CurrentDomain.SetupInformation);

        Type type = typeof(T);

        _value = (T)_domain.CreateInstanceAndUnwrap(type.Assembly.FullName, type.FullName);
    }

    public T Value
    {
        get
        {
            return _value;
        }
    }

    public void Dispose()
    {
        if (_domain != null)
        {
            AppDomain.Unload(_domain);

            _domain = null;
        }
    }
}

and I wrote this code below, my expectation is it would not crush the process, but it does.

public class Work : MarshalByRefObject
{
    public void DoSomething()
    {
        Thread thread = new Thread(new ThreadStart(() =>
        {
            throw new Exception();
        }));

        thread.IsBackground = true;

        thread.Start();

        while (true)
        {
            System.Diagnostics.Trace.WriteLine("Hello from main thread");
        }
    }
}

    protected void Page_Load(object sender, EventArgs e)
    {
        using (Isolated<Work> isolated = new Isolated<Work>())
        {
            isolated.Value.DoSomething();
        }
    }

Can you please help me understand what I'm doing wrong?

Y.S
  • 1,860
  • 3
  • 17
  • 30
  • 1
    Your code producesses an unhandled exception that will kill your application regardless of the appdomain it is thrown. – Jehof Aug 17 '15 at 12:37
  • But isn't one of the purposes of AppDomain is to address such a scenario? For example, If I use a 3rd party plugin beta version I import to production environment application? – Y.S Aug 17 '15 at 12:38
  • Also, please refer to this post which mentions it in the answers comment: http://stackoverflow.com/questions/1094478/what-is-a-net-application-domain – Y.S Aug 17 '15 at 12:39
  • 1
    I´m not sure. Heres a good article explaining some details http://www.codeproject.com/Articles/635497/AppDomains-Wont-Protect-Host-From-a-Failing-Plugin – Jehof Aug 17 '15 at 12:39
  • This is a great post! thanks a lot, it explained that the "termination of the process cannot be stopped" which was the bottom line I was looking for. – Y.S Aug 17 '15 at 12:51

1 Answers1

0

There is no way to prevent the process termination.

As suggested by @Jehof,

More info here: http://www.codeproject.com/Articles/635497/AppDomains-Wont-Protect-Host-From-a-Failing-Plugin

Y.S
  • 1,860
  • 3
  • 17
  • 30