lundi 17 août 2015

Why this code which runs on seperate AppDomain Crashes my process?

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?





Aucun commentaire:

Enregistrer un commentaire