We are doing extensive code analysis on a LOT (thousands) of C# projects. But although we are not calling the Solution.Emit() method, assemblies are still loaded into memory. Are there other methods that also cause this behavior? Is it even possible at all to create a compilation and retrieve its symbols, without loading an assembly in memory? Hopefully we can somehow avoid to create separate appdomains and unloading them.
Asked
Active
Viewed 302 times
1
-
Does any of the classes of your code implement `IDisposable`? If they do, check how are you handling the resources. – Cleptus Oct 28 '21 at 06:14
-
As far as I know there is no way to unload an assembly when already loaded, so in the first place we will need to prevent that the assembly is being loaded. – TWT Oct 28 '21 at 06:43
-
Not per-se, but you should be able to get it done creating a new AppDomain. Check my answer and if you find it useful mark it. Note that because of lack of a sample [mcve] I was only able to give you some generic code that should be able to guide you. – Cleptus Oct 28 '21 at 08:46
1 Answers
1
looks like your approach is wrong, you are likely loading the assemblies in the primary AppDomain.
But the documentation How to: Load and unload assemblies says that to unload an assembly you need yo unload the full application domain where those assemblies were loaded. It also links to How to: Unload an Application Domain
So you should:
- Create a new Application Domain for the assembly
- Load the assembly into the new AppDomain
- Do your code analysis
- Unload that assembly specific Appication Domain
This is the code from the doc:
Console.WriteLine("Creating new AppDomain.");
AppDomain domain = AppDomain.CreateDomain("MyDomain", null);
Console.WriteLine("Host domain: " + AppDomain.CurrentDomain.FriendlyName);
Console.WriteLine("child domain: " + domain.FriendlyName);
try
{
AppDomain.Unload(domain);
Console.WriteLine();
Console.WriteLine("Host domain: " + AppDomain.CurrentDomain.FriendlyName);
// The following statement creates an exception because the domain no longer exists.
Console.WriteLine("child domain: " + domain.FriendlyName);
}
catch (AppDomainUnloadedException e)
{
Console.WriteLine(e.GetType().FullName);
Console.WriteLine("The appdomain MyDomain does not exist.");
}

Cleptus
- 3,446
- 4
- 28
- 34
-
-
To reduce the performance impact of the proposed solution you could analize some assembiles in the created `AppDomain` and then unload it, reuse it for a few assemblies. Just find your sweet spot based on your current resources (memory/cpu/time) – Cleptus Nov 01 '21 at 22:05