Programming with AppDomainsTo illustrate how to program with AppDomains, we are going to create a solution that has a console application and a class library. The code in the console application is going to create a new AppDomain and use that new AppDomain to execute code within the class library. When that secondary code is finished executing, the code in the console application will then unload the temporary AppDomain, illustrating how you can gain tight control over the memory consumption of your application by manually loading and unloading certain AppDomains. The code for the class library is shown in Listing 12.5. Listing 12.5. A Class Library with Simple Code for Displaying the AppDomain's Loaded Assembly List
Listing 12.6 shows the code that creates a new AppDomain and executes code within it. Listing 12.6. Creating and Unloading an AppDomain
To prove that the work is being executed in a separate AppDomain, the output of the preceding code looks as follows: [AppDomainSample.vshost.exe] Main Application starting. Main AppDomain has 11 Assemblies Loaded. [WorkerDomain] Doing some work. [WorkerDomain] Domain-Wide value is How much wood could a woodchuck chuck... This domain currently has 3 Assemblies loaded. mscorlib Microsoft.VisualStudio.HostingProcess.Utilities SecondaryCode Working with AppDomains may not be something that you do every day as a .NET developer, but being armed with the knowledge of how they work and how they fit into the overall architecture of the framework will help you create better applications. |