Implement C# Generic Timeout

后端 未结 7 1870
谎友^
谎友^ 2020-11-22 09:39

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 t         


        
7条回答
  •  误落风尘
    2020-11-22 10:02

    This is how I'd do it:

    public static class Runner
    {
        public static void Run(Action action, TimeSpan timeout)
        {
            IAsyncResult ar = action.BeginInvoke(null, null);
            if (ar.AsyncWaitHandle.WaitOne(timeout))
                action.EndInvoke(ar); // This is necesary so that any exceptions thrown by action delegate is rethrown on completion
            else
                throw new TimeoutException("Action failed to complete using the given timeout!");
        }
    }
    

提交回复
热议问题