Unloading AppDomains
Asked Answered
S

1

6

Supose I have AppDomainA, which spins up AppDomainB. AppDomainB then spins up AppDomainC.

If, within AppDomainA I unload AppDomainB, does AppDomainC also get unloaded or must I make sure to handle that on my own?

Snowplow answered 28/3, 2014 at 12:34 Comment(1)
An appdomain isn't "owned" by anybody. It therefore has to be explicitly unloaded if process termination isn't the preferred way. They also cannot be iterated, you have to keep a reference to the AppDomain object around so you can call its Unload method.Wolfsbane
P
1

Best way to find out is to try it. Here is an example of creating AppDomainA, which creates AppDomainB. We tell B to do some work, and unload A.

internal class Program
{
    private static Timer _timer;
    private static void Main(string[] args)
    {
        var domainA = AppDomain.CreateDomain("AppDomainA");
        domainA.DomainUnload += (s, e) => Console.WriteLine("DomainA was unloaded.");
        domainA.DoCallBack(() =>
        {
            var domainB = AppDomain.CreateDomain("AppDomainB");
            domainB.DomainUnload += (s, e) => Console.WriteLine("DomainB was unloaded.");
            domainB.DoCallBack(() =>
            {
                _timer = new Timer(o =>
                {
                    Console.WriteLine("Tick from AppDomain: " + AppDomain.CurrentDomain.FriendlyName);
                }, null, 0, 1000);
            });
        });
        AppDomain.Unload(domainA);
        Application.Run(); //Run a message loop so AppDomainB can keep doing work.
    }
}

We see we get the message AppDomainA was unloaded, but not B, and B keeps working. Our conclusion is you need to make sure to handle this on your own.

Pella answered 28/3, 2014 at 12:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.