0

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 ?

4

1 回答 1

1

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);
于 2014-06-17T05:38:26.590 回答