我在用Thread.Join(int millisecondsTimeout) http://msdn.microsoft.com/en-us/library/6b1kkss0%28v=vs.90%29.aspx终止一些AppDomain
s.
我经常收到一条错误消息,指出 AppDomain 未在 5 秒内终止。在单步执行调试器时,我看到AppDomain.Unload()
通话在 5 秒内轻松终止,但是Thread.Join
返回假。
我哪里错了?
var thread = new Thread(
() =>
{
try
{
AppDomain.Unload(someAppDomain);
}
catch (ArgumentNullException)
{
}
catch (CannotUnloadAppDomainException exception)
{
// Some error message
}
});
thread.Start();
const int numSecondsWait = 5;
if (!thread.Join(1000 * numSecondsWait))
{
// Some error message about it not exiting in 5 seconds
}
Edit 1
值得添加的内容AppDomain
是的。每个AppDomain
至少有一个Timer http://msdn.microsoft.com/en-us/library/system.threading.timer.aspx。代码大致如下所示,(请记住,为了便于阅读,我已将大量类折叠到一个类中)。
static void Main(string[] args)
{
_exceptionThrown = new EventWaitHandle(false, EventResetMode.AutoReset);
_timer = new Timer(TickAction, null, 0, interval);
try
{
_exceptionThrown.WaitOne();
}
finally
{
_timer.Dispose(_timerWaitHandle);
WaitHandle.WaitAll(_timerWaitHandle);
}
}
实际上我知道“主”线程会抛出一个ThreadAbortException http://msdn.microsoft.com/en-us/library/system.threading.threadabortexception.aspx,跳到finally语句并确保Timer
队列在退出之前已完全排空。
全部Timer
当它们位于 tick 方法内时,会记录日志。所以我几乎可以肯定计时器队列上没有任何内容,并且_timer.Dispose(_timerWaitHandle)
立即返回。
不管有没有,至少one三个中的AppDomain
s I am Unload
ing 不会在 5 秒内完成。