Search code examples
c#.nethttpwebrequesttry-catchsystem.net.webexception

How to make a function return after a specific amount of time


I have a Proxy testing function. Inside it I have a catch block and after a specified amount of time (TIMEOUT) if the proxy is not good I return a false flag. The problem is that once every 10 times the function hangs even though there's no exception present . Practically the HttpWebResponse.Timeout doesn't work correctly (or maybe it does but I don't know how to use it). How do I make the method return a false flag automatically after a specific amount of time in case my try...catch doesn't capture all errors ?


Solution

  • Couldnt find link, that solution i found on SO a while ago.

    public class TimeoutInvoker
    {
        public static void Run(Action action, int timeout)
        {
            var waitHandle = new EventWaitHandle(false, EventResetMode.ManualReset);
            AsyncCallback callback = ar => waitHandle.Set();
            action.BeginInvoke(callback, null);
    
            if (!waitHandle.WaitOne(timeout))
                throw new TimeoutException("Timeout.");
        }
    }
    

    Just use your action and timeout as args. Example:

    TimeoutInvoker.Run(()=>LongRunningFunction(), 60000);