ExecuteAsync with ResilienceContext and CancellationToken #2133
-
Hello, I wasn't able to find an This can be done with AsyncPolicy. My use-case:
I'm unable to do this in Polly v8 - the Here is some sample code public class MyService(ILogger logger,
ResiliencePipelineProvider<string> pipelineProvider,
AsyncPolicy asyncPolicy,
ISomethingAsync foo) : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken) {
var pipeline = pipelineProvider.GetPipeline("MyPipeline");
while (!stoppingToken.IsCancellationRequested)
{
//new way
var resilienceContext = ResilienceContextPool.Shared.Get(stoppingToken);
resilienceContext.Properties.Set(new ResiliencePropertyKey<ILogger>("Logger"), logger);
try
{
//something like this, but this method signature doesn't exist
var resultNew = await pipeline.ExecuteAsync(async (ctx, token) =>
{
ctx.Properties.Set(new ResiliencePropertyKey<string>("SomeKey"), "SomeValue");
var bar = await foo.GetAsync(token);
return bar;
}, resilienceContext, stoppingToken);
}
finally
{
ResilienceContextPool.Shared.Return(resilienceContext);
}
//pre version 8 - works
var context = new Context();
context.Add("Logger", logger);
var resultOld = await asyncPolicy.ExecuteAsync(async (ctx, token) =>
{
ctx["SomeKey"] = "SomeValue";
var bar = await foo.GetAsync(token);
return bar;
}, context, stoppingToken);
}
}
} Hope this makes sense. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 4 replies
-
The reason there aren't any overloads where both are available is because the cancellation token is a member of the resilience context: Polly/src/Polly.Core/ResilienceContext.cs Line 34 in 0856394 |
Beta Was this translation helpful? Give feedback.
-
Thank you for this (and other) clarifications. I wasn't aware of that. I ran it through the debugger and indeed these 2 tokens are different in v8: var res = await pipeline.ExecuteAsync(async (innerToken) =>
{
var bar = await foo.GetAsync(innerToken);
return bar;
}, outsideToken); but are the same in v7 equivalent code. |
Beta Was this translation helpful? Give feedback.
Polly v7 had far too many method overloads which made future iteration and maintenance difficult, so we rationalised down the number of overloads for v8. We also made other changes to improve performance, such as pooling contexts.
If you want to use both features (context and cancellation) then the shared snippet is the way to achieve this. You could simplify the code to some degree by adding helper methods specific to your context to do things like get/set your values on your
ResilienceContext
via methods that abstract away the resilience keys etc: example.The inner token in the lambda will/should be different if you're using strategies like timeout and hedging, so I would avoid writing…