Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions src/Polly.Core/Hedging/HedgingResilienceStrategy.cs
Original file line number Diff line number Diff line change
Expand Up @@ -67,12 +67,16 @@ private async ValueTask<Outcome<T>> ExecuteCoreAsync<TState>(
ResilienceContext context,
TState state)
{
// Capture the original cancellation token so it stays the same while hedging is executing.
// If we do not do this the inner strategy can replace the cancellation token and with the concurrent
// nature of hedging this can cause issues.
var cancellationToken = context.CancellationToken;
var continueOnCapturedContext = context.ContinueOnCapturedContext;

var attempt = -1;
while (true)
{
attempt++;
var continueOnCapturedContext = context.ContinueOnCapturedContext;
var cancellationToken = context.CancellationToken;
var start = _timeProvider.GetTimestamp();
if (cancellationToken.IsCancellationRequested)
{
Expand Down
22 changes: 22 additions & 0 deletions test/Polly.Core.Tests/Hedging/HedgingResilienceStrategyTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,28 @@ public void ExecutePrimaryAndSecondary_EnsureAttemptReported()
attempts[1].Attempt.Should().Be(1);
}

[Fact]
public async Task ExecutePrimary_Cancelled_SecondaryShouldBeExecuted()
{
_options.MaxHedgedAttempts = 2;

ConfigureHedging(o => o.Result == "primary", args => () => Outcome.FromResultAsTask("secondary"));
var strategy = Create();

var result = await strategy.ExecuteAsync(
context =>
{
var source = new CancellationTokenSource();
source.Cancel();
context.CancellationToken = source.Token;

return new ValueTask<string>("primary");
},
ResilienceContext.Get());

result.Should().Be("secondary");
}

[InlineData(-1)]
[InlineData(-1000)]
[InlineData(0)]
Expand Down