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’.