Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assemblies not unloading after AppDomain unload?

I'm using an AppDomain in order to load assemblies and then unload them.

However, I'm having a very strage problem. After the AppDomain is unloaded - I can still see in process explorer that some assemblies are loaded multiple times! Why are there remainders of the loaded assemblies? Doesn't an AppDomain.Unload frees all the AppDomain's loaded memory?

You can see in the attached image:

Total AppDomains are 3 (I created 3 AppDomains in the process's life-cycle)

AppDomains: 1 (Currently only 1 AppDomain exists)

And for some reason, as you can see in the loaded DLL section bellow - Assemblies are loaded multiple times into the process..

Code:

AppDomain fetcherDomain = AppDomain.CreateDomain("StatusFetcher");
try
{
    var fetcher = (LocalStatusFetcher)fetcherDomain.CreateInstanceFromAndUnwrap(Assembly.GetExecutingAssembly().CodeBase, typeof(LocalStatusFetcher).FullName);
    //doing some other stuff that is not interesting...
}
finally
{
    AppDomain.Unload(fetcherDomain);
}

And yes, LocalStatusFetcher does inherit MarshalByRefObject...

enter image description here

like image 649
Roy Reznik Avatar asked Nov 18 '12 12:11

Roy Reznik


1 Answers

There's a very high possibility that the assemblies you're loading into the foreign application domain are being bled into the current one. There are tons of ways that this can happen, but your problem in particular is passing Assembly.GetExecutingAssembly().CodeBase to the CreateInstanceFromAndUnwrap method. A call to Assembly.GetExecutingAssembly() loads the currently executing assembly into the current app domain, and passing the .CodeBase property to CreateInstanceFromAndUnwrap will attempt to load the target assembly (located in the application path or in the GAC) into the target domain before instantiating your target proxy. Currently, I see nothing wrong with this code other than the possible bleeding issue.

If you have multiple application domains then you'll see multiple copies of the assembly in the LoadFrom context because the only assembly that is shared across AppDomains is mscorlib.dll. Unless I'm misunderstanding your question I think what you're seeing is normal.

like image 141
Jduv Avatar answered Sep 17 '22 17:09

Jduv