[英]Polly Policy.TimeoutAsync not giving TimeoutRejected exception
Here is my sample code:这是我的示例代码:
var timeoutPolicy = Policy.TimeoutAsync(TimeSpan.FromMilliseconds(_configOptions.ResponseTimeout), TimeoutStrategy.Pessimistic);
try
{
return await timeoutPolicy.ExecuteAsync(async ct => await Somemethod(request, ct), CancellationToken.None);
}
catch (TimeoutRejectedException ex)
{
_//Some logging to go here/
}
configOptions.ResponseTimeout
is configured in config file, I am expecting the method await Somemethod(request, ct)
, CancellationToken.None
should throw TimeoutRejectedException
based on the value given in config. configOptions.ResponseTimeout
在配置文件中配置,我期待方法await Somemethod(request, ct)
, CancellationToken.None
应该根据配置中给出的值抛出TimeoutRejectedException
。
But it is not throwing any exception.但它没有抛出任何异常。 Can anyone please help me to identify where I am going wrong?
谁能帮我确定我哪里出错了?
Help will be much appreciated.帮助将不胜感激。
The delegate does support cancellation.委托确实支持取消。
private static async Task SomeMethodAsync(CancellationToken ct = default)
{
Console.WriteLine($"{nameof(SomeMethodAsync)} has been called.");
await Task.Delay(15000, ct); //It is aware of the CancellationToken
}
private static AsyncTimeoutPolicy GetTimeoutPolicy
=> Policy
.TimeoutAsync(
TimeSpan.FromMilliseconds(1000),
TimeoutStrategy.Optimistic,
(context, timeout, _, exception) =>
{
Console.WriteLine($"{"Timeout",-10}{timeout,-10:ss\\.fff}: {exception.GetType().Name}");
return Task.CompletedTask;
});
var strategy = GetTimeoutPolicy;
var result = await strategy.ExecuteAsync(async (ct) => await SomeMethodAsync(ct), CancellationToken.None);
SomeMethodAsync has been called.
Timeout 01.000 : TaskCanceledException
Unhandled exception. Polly.Timeout.TimeoutRejectedException: The delegate executed asynchronously through TimeoutPolicy did not complete within the timeout.
---> System.Threading.Tasks.TaskCanceledException: A task was canceled.
...
The delegate does not support cancellation.委托不支持取消。
private static async Task SomeMethodAsync(CancellationToken ct = default)
{
Console.WriteLine($"{nameof(SomeMethodAsync)} has been called.");
await Task.Delay(15000); //It is NOT aware of the CancellationToken
}
private static AsyncTimeoutPolicy GetTimeoutPolicy
=> Policy
.TimeoutAsync(
TimeSpan.FromMilliseconds(1000),
TimeoutStrategy.Pessimistic,
(context, timeout, _, exception) =>
{
Console.WriteLine($"{"Timeout",-10}{timeout,-10:ss\\.fff}: {exception.GetType().Name}");
return Task.CompletedTask;
});
var strategy = GetTimeoutPolicy;
var result = await strategy.ExecuteAsync(async () => await SomeMethodAsync());
SomeMethodAsync has been called.
Timeout 01.000 : TaskCanceledException
Unhandled exception. Polly.Timeout.TimeoutRejectedException: The delegate executed asynchronously through TimeoutPolicy did not complete within the timeout.
---> System.Threading.Tasks.TaskCanceledException: A task was canceled.
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.