超时模式 - 如何不好是真的Thread.Abort的? [英] Timeout Pattern - How bad is Thread.Abort really?
问题描述
我在不同的网站,Thread.Abort的不是很好用阅读。在这种情况下,你如何实现超时模式?举例来说,我读过,MS使用下面的模式(我已经包裹在一个扩展方法)在整个框架。就个人而言,我认为这是一个pretty酷扩展,但我担心的Thread.Abort的。有没有人有更好的办法?
公共静态布尔CallandWait(此行动对行动,诠释超时)
{
线程的子线程= NULL;
行动wrappedAction =()=>
{
子thread = Thread.CurrentThread;
行动();
}; IAsyncResult的结果= wrappedAction.BeginInvoke(NULL,NULL); 如果(((超时= -1)及!&安培;!result.IsCompleted)及和放大器;!(result.AsyncWaitHandle.WaitOne(超时,FALSE)|| result.IsCompleted))
{
如果(子thread!= NULL)
{
subThread.Abort();
} 返回false;
}
其他
{
wrappedAction.EndInvoke(结果);
返回true;
}
}
的潜在的很不好。
中止的线程可以离开共享状态损坏,可以离开异步操作运行,...
请参阅乔·达菲的博客:<一href=\"http://www.bluebytesoftware.com/blog/2009/03/13/Managed$c$cAndAsynchronousExceptionHardening.aspx\">\"Managed code和异步异常硬化。
I've read at various websites that Thread.Abort is not very good to use. In this case, how do you implement a timeout pattern? For instance, I've read that MS uses the pattern below (which I've wrapped in an extension method) throughout the framework. Personally, I think this is a pretty cool extension, but I'm worried about the Thread.Abort. Does anyone have a better way?
public static bool CallandWait(this Action action, int timeout)
{
Thread subThread = null;
Action wrappedAction = () =>
{
subThread = Thread.CurrentThread;
action();
};
IAsyncResult result = wrappedAction.BeginInvoke(null, null);
if (((timeout != -1) && !result.IsCompleted) && (!result.AsyncWaitHandle.WaitOne(timeout, false) || !result.IsCompleted))
{
if (subThread != null)
{
subThread.Abort();
}
return false;
}
else
{
wrappedAction.EndInvoke(result);
return true;
}
}
Potentially very bad.
The aborted thread could leave shared state corrupted, could leave asynchronous operations running, ...
See Joe Duffy's blog: "Managed code and asynchronous exception hardening".
这篇关于超时模式 - 如何不好是真的Thread.Abort的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!