why cannot catch exception when using Policy's TimeoutAsync

28 views Asked by At

below is the code:

public class Example
{
    public static async Task Main()
    {
        try
        {
            var timeoutPolicy = Policy.TimeoutAsync(TimeSpan.FromSeconds(5), TimeoutStrategy.Optimistic);

            var cancellationTokenSource = new CancellationTokenSource();
            var cancellationToken = cancellationTokenSource.Token;

            var task = timeoutPolicy.ExecuteAsync(c => Task.Delay(TimeSpan.FromSeconds(10), c), cancellationToken);
     
            await task;
        }      
        catch (TimeoutRejectedException exception)
        {

        }
        catch (Exception exception)
        {

        }
    }
}

when I ran the code, my code doesn't catch any exception despite the fact that I am using catch (Exception exception).

Instead, the VS throws another exception from AsyncTimeoutEngine as picture below shows

enter image description here

but it re-throw the exception, so why I am still not able to catch the exception?

1

There are 1 answers

0
Peter Csala On BEST ANSWER

AsyncTimeoutEngine is the Polly V7 implementation of the timeout policy. Most probably your Visual Studio (Code) is setup in a way that it should stop execution whenever an exception is thrown.

Check your exception settings under Debug > Windows > Exception Settings.


Side note: Your example does not need cancellationTokenSource and cancellationToken. You can simple pass CancellationToken.None to the ExecuteAsync

await timeoutPolicy.ExecuteAsync(
   c => Task.Delay(TimeSpan.FromSeconds(10), c),
   CancellationToken.None);