Twitter GitHub Facebook Instagram dirv.me

Daniel Irvine on building software

Our .NET AppDomain nightmare, part 2

17 January 2013

In my last post I talked about the characteristics of an AppDomain that cause it to behave differently from threads or processes. An AppDomain is like a container that stays resident as long as its owner wishes it, and doesn’t automatically terminate when its work is finished. Read that post for a rundown of the problem we were facing.

Today we solved our problem by modifying the semantics of our host processing; we shifted responsibility of the post processing from the host AppDomain to the first child AppDomain to be loaded. We call this the “primary” AppDomain, and it now runs a series of process-wide tasks once it completes. In other words the binary interface hasn’t changed for our users but we now expect that their first designated AppDomain will live at least as long as all the other AppDomains that are launched in the process.

It just so happens this is true for all our current deployed user modules, so it’s a nice fit. Now we just need to make sure it’s well documented and that our users are aware of it.

An added benefit of this design is that the host AppDomain can actually be unloaded once it has successfully loaded all user modules have started up.

Implementation wise, I begin work in the AppDomain with a call to AppDomain.CreateInstance, passing in one of two types depending on whether the AppDomain is primary or not. This works well for us, but you can also use AppDomain.GetData and AppDomain.SetData to push this kind of configuration data into your AppDomain entrypoint.

This has been very cathartic for me... And hopefully I’ll never have to write about AppDomains again. If you’re thinking about using AppDomains within your .NET project, here’s my advice:

  1. Don’t do it unless you really, really have to. Can you use process isolation instead?
  2. Be absolutely aware that AppDomains do not behave exactly like processes, or like threads. They are an entirely different concept but they will have been sold to you as “lightweight processes”.

About the author

Daniel Irvine is a software craftsman at 8th Light, based in London. These days he prefers to code in Clojure and Ruby, despite having been a C++ and C# developer for the majority of his career.

For a longer bio please see danielirvine.com. To contact Daniel, send a tweet to @d_ir or use the comments section below.

Twitter GitHub Facebook Instagram dirv.me