我Thread.Join(int millisecondsTimeout)
用来终止一些AppDomain
s.
我经常收到一条错误消息,指出 AppDomain 未在 5 秒内终止。在单步调试器中,我看到AppDomain.Unload()
调用在 5 秒内轻松终止,但Thread.Join
返回 false。
我哪里错了?
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
}
编辑 1
值得添加每个AppDomain
s 所做的事情。每个AppDomain
人至少有一个Timer
。代码大致如下所示,(请记住,为了便于阅读,我已将大量类合并为一个类)。
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
, 跳转到 finally 语句并确保Timer
队列在退出之前完全排空。
Timer
当它们在 tick 方法中时,所有的s 都会记录下来。所以我几乎可以肯定计时器队列中没有任何内容,并且_timer.Dispose(_timerWaitHandle)
立即返回。
不管做与不做,至少三个我ing中的一个不会在5秒内完成。AppDomain
Unload