I have been doing testing of remoting using AppDomains but I have unfortunately run across a snag when unloading those AppDomains. An attempt to unload an AppDomain consistently seems to throw an exception the second time I initialize and then unload the app domain. The error message is, "AppDomain can not be unloaded because the thread 954 can not be unwound out of it." (Obviously with the thread id varying for each run.)
I initialize the AppDomain using the following code:
public void InitializeRemotingHostAppDomain() { AppDomainSetup setup = new AppDomainSetup(); setup.ApplicationBase = CodeBase.Path(); Evidence baseEvidence = AppDomain.CurrentDomain.Evidence; Evidence evidence = new Evidence(baseEvidence);
RemotingHostAppDomain = AppDomain.CreateDomain( "Client Domain", evidence, setup); RemotingHostAppDomain.InitializeLifetimeService(; }
... and the unload code looks like this:
public void UnInitializeRemotingHostAppDomain() { // Unload Appdomain if(RemotingHostAppDomain != null) { AppDomain.Unload(RemotingHostAppDomain); RemotingHostAppDomain=null; } }
From what I can tell there is no Dispose() method on AppDomain that I have neglected to call or anything. And yet, I suspect that this is a garbage-collector-not-yet-run type of issue. The reason I suspect this is if I wait long enoug between repeated exections of the above code then everything seems to work.
To work around the issue generically I tried to catch the exception and retry the unload until it worked:
public void UnInitializeRemotingHostAppDomain() { CannotUnloadAppDomainException cannotUnloadException = null; int count=0;
// Unload Appdomain if(RemotingHostAppDomain != null) { do { cannotUnloadException = null; try { AppDomain.Unload(RemotingHostAppDomain); } catch(CannotUnloadAppDomainException exception) { cannotUnloadException = exception; count++; } } while(cannotUnloadException != null);
RemotingHostAppDomain=null; System.Diagnostics.Trace.WriteLineIf((count!=0), string.Format("THE COUNT IS: {0}", count)); } }
Although this seemed to improve the reliability significantly it still wasn't 100% reliable. Furthermore, although the reliability was improved, often the trace message didn't appear in the debug window indicating that, in fact, an exception had been thrown.
One of the problems with AppDomain.UnLoad() is that it often generates a ThreadAbortException as follows:
An unhandled exception of type 'System.Threading.ThreadAbortException' occurred in Unknown Module.
It is not clear to me at the moment how this can be avoided. For the moment, this issues surrounding AppDomain.UnLoad() remain unresolved.
2:53:47 AM
|