Q: Implement C# Generic Timeout

D: I am looking for good ideas for implementing a generic way to have a single line (or anonymous delegate) of code execute with a timeout.
TemperamentalClass tc = new TemperamentalClass();
tc.DoSomething();  // normally runs in 30 sec.  Want to error at 1 min
I'm looking for a solution that can elegantly be implemented in many places where my code interacts with temperamental code (that I can't change).
In addition, I would like to have the offending "timed out" code stopped from executing further if possible.

Test Case #9


File ID: #299273-1-cc


public class ThreadingUtils
{
    public static bool CallWithTimeout (Action action, int timeoutMilliseconds)
    {
        Thread threadToKill = null;
        Action wrappedAction = () = > {
            threadToKill = Thread.CurrentThread;
            action ();
        };
        IAsyncResult result = wrappedAction.BeginInvoke (null, null);
        if (result.AsyncWaitHandle.WaitOne (timeoutMilliseconds)) {
            wrappedAction.EndInvoke (result);
            return true;
        } else {
            threadToKill.Abort ();
            return false;
        }
    }
}

  1. I can not believe this is the accepted answer, someone must not be reading the comments here, or the answer was accepted before the comments and that person does not check his replies page. Thread.Abort is not a solution, it's just another problem you need to solve!
  2. You are the one not reading the comments. As chilltemp says above, he's calling code that he has NO control over - and wants it to abort. He has no option other than Thread.Abort() if he wants this to run within his process. You are right that Thread.Abort is bad - but like chilltemp says, other things are worse!
  3. Thread.Abort() is very dangerous to use, It should not be used with regular code, only code that is guaranteed to be safe should be aborted, such as code that is Cer.Safe, uses constrained execution regions and safe handles. It should not be done for any code.

Comments Quality
Accurate?:
Precise?:
Concise?:
Useful?: