views:

307

answers:

4

From what-is-a-net-application-domain:

You can run several application domains in a single process with the same level of isolation that would exist in separate processes, but without incurring the additional overhead of making cross-process calls or switching between processes.

I would like to understand more about how/why one would actually use multiple AppDomains in their application. Can anyone provide an example with actual code snippets?

+1  A: 

I have use this in this context (dont have the code handy with me right now to post)

  • Create a new app domain (e.g. appDomainX)
  • Create a new instance of an object using this new domain
  • The new object (lived in the new object) load a bunch of assemblies
  • Reflect on them to collect some metrics
  • Get the result produced
  • Unload appDomainX

The benefit of this is that you can unload assemblies loaded previously loaded into the newly created appDomain. If you are doing this on your main appDomain over and over again loading more assemblies, your appDomain will grow monstrously. Creating a separate appDomain allows you to unload after each inspection which in turn unload all the assemblies loaded to that domain hence the main appDomain remains clean

Fadrian Sudaman
+2  A: 

Reading the MSDN actually provides some good information.

http://msdn.microsoft.com/en-us/library/system.appdomain.aspx

--Dan

Dan
A: 

I worked on a piece of (mostly) C++ software that allowed users to write scripts to automate the application using C#, or VB.NET. The application also had a few of its components written in C#. It used one AppDomain for the program components, and another to sandbox the scripts.

The original implementation of scripting created an AppDomain for each script, but that proved to be too slow and it prevented some useful script behaviors, so we went to one permanent AppDomain for the script engine.

John Knoeller
A: 

You might want to use one to simulate the processing of IIS. You need a long running process that leaks memory. You can keep track of how many requests on AD has processed and one you reach a threshold, spin up a new one. When the old one has finished all processing unload it and let the CLR clean up some of the app junk.

Don't ask me how I know this. :)

You might also do this if you want to run code in different security contexts.

No Refunds No Returns