Unloading Custom App Domain C# with Example



Unloading Custom App Domain C# with Example

 using System;
using System.Linq;
using System.IO;

namespace CSharpMultiThreading
{
	class CustomApplicationDomain
	{
		static void Main(string[] args)
		{
			// Show all loaded assemblies in default AppDomain.
			AppDomain defaultAD = AppDomain.CurrentDomain;
			
			defaultAD.ProcessExit += (o, s) =>{Console.WriteLine("Default AD unloaded!");};
			
			ListAllAssembliesInAppDomain(defaultAD);
			MakeNewAppDomain();
		}

		private static void MakeNewAppDomain()
		{
			// Make a new AppDomain in the current process.
			AppDomain newAD = AppDomain.CreateDomain("SecondAppDomain");
			
			try
			{
				// Now load CarLibrary.dll into this new domain.
				newAD.Load("MyLibrary");
			}
			catch (FileNotFoundException ex)
			{
				Console.WriteLine(ex.Message);
			}
			
			// List all assemblies.
			ListAllAssembliesInAppDomain(newAD);
			
			// Now tear down this AppDomain.
			AppDomain.Unload(newAD);
		}
		
		static void ListAllAssembliesInAppDomain(AppDomain ad)
		{
			// Now get all loaded assemblies in the default AppDomain.
			var loadedAssemblies = from a in ad.GetAssemblies() orderby a.GetName().Name select a;
			Console.WriteLine("**** Here are the assemblies loaded in {0} ****", ad.FriendlyName);
			
			foreach (var a in loadedAssemblies)
			{
				Console.WriteLine("-> Name: {0}", a.GetName().Name);
				Console.WriteLine("-> Version: {0}\n", a.GetName().Version);
			}
		}
	}
}
 

0 Comment's

Comment Form

Submit Comment