I'm trying to unload an AppDomain and I get CannotUnloadAppDomainException
.
MSDN mentions 3 reasons why this exception could be thrown:
- The default application domain, which must remain loaded during the lifetime of the application.
- An application domain with a running thread that cannot immediately stop execution.
- 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. SinceAppDomain.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?