2

I'm trying to unload an AppDomain and I get CannotUnloadAppDomainException.

MSDN mentions 3 reasons why this exception could be thrown:

  1. The default application domain, which must remain loaded during the lifetime of the application.
  2. An application domain with a running thread that cannot immediately stop execution.
  3. An application domain that has already been unloaded.

My application suffers from the case 2).

It has some background threads - for example I have a search indexing thread running its own Dispatcher.

As far as I know, when I call

AppDomain.Unload(subDomain);

then all threads in the affected domain get a ThreadAbortException.

Ideally that would mean that all threads are "killed" / stopped, right?

Except in two cases:

  • When a thread calls some managed code - bad luck...
  • When a thread executes some code in a finally statement.

It seems that my application does the first (probably it calls some unmanaged code under hood, that's why it doesn't stopped)

So the big question is: how to unload the AppDomain if it has multiple threads?

I see only two options:

  • try to abort my threads then somehow recheck the state of the threads. If they are stopped, then I can call AppDomain.Unload - it shouldn't throw an exception.
  • another alternative is just simply call AppDomain.Unload. Probably it will throw an exception. Then I can catch this exception and retry the unloading. Since AppDomain.Unload tries to abort all the affected threads, probably a few retry would be enough.

Both solutions use some retry mechanism which seems to be hackish.

Isn't there some simpler, more robust way to do this in .NET?

Zsolt
  • 3,263
  • 3
  • 33
  • 48

1 Answers1

3

You don't want ThreadAbortedExceptions to avoid this consider some sort of Cancellation Policy. If you have access to these threads or task then you can make use of Cancellation in main threads

If you for some reason you don't have any control over background threads, then unfortunately there is not much that can be done. Other than what's already described in this answer

This is the best answer I personally could give you to have a clear graceful shutdown of your child domain. Anything else will be just messy.

Community
  • 1
  • 1
Stan R.
  • 15,757
  • 4
  • 50
  • 58