我在各种网站上看到Thread.Abort不是很好用.在这种情况下,如何实现超时模式?例如,我已经读过MS在整个框架中使用下面的模式(我已经用扩展方法包装).就个人而言,我认为这是一个非常酷的扩展,但我担心Thread.Abort.有没有人有更好的方法?
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;
}
}
Run Code Online (Sandbox Code Playgroud)