问题描述
这是我的示例代码:
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
在配置文件中配置,我期待方法 await Somemethod(request,ct)
,CancellationToken.None
应该根据配置中给出的值抛出 TimeoutRejectedException
。
但它没有抛出任何异常。 谁能帮我找出我哪里出错了?
非常感谢您的帮助。
解决方法
乐观超时
代表确实支持取消。
要执行的委托
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.
...
悲观超时
委托不支持取消。
要执行的委托
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,-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.
...