I am trying to use the Polly package in C#. I want to run some code and then, if it fails, wait and retry. Currently my loop looks similar to this:
var successful = false
while (!successful){
// Try to perform operation.
successful = TryToDoStuff()
if (!successful){
// Wait, then retry.
await Task.WhenAny(
taskCompletionSource1.Task,
taskCompletionSource1.Task,
Task.Delay(TimeSpan.FromSeconds(10)));
}
}
I.e.: Wait 10 seconds OR until one of these task completion sources gets a signal and terminates. Then retry.
What I want to do is something like this (which is not supported by the Polly API):
Policy
.Handle<RetryException>()
.WaitAndRetryForever(
Task.WhenAny(
taskCompletionSource1.Task,
taskCompletionSource1.Task,
Task.Delay(TimeSpan.FromSeconds(10))))
.Execute(TryToDoStuff); // Method TryToDoStuff will throw RetryException if it fails
Is it possible to do something like this with Polly? Can I wait for anything other than a TimeSpan?
Regarding the two tasks I await in the above example: One task is a cancellation indicating that the entire thing should shut down. The other is a "wake up for connection attempt" task whose termination indicates that "this object's state has changed; try to call it again". In both cases I want my loop to continue to the next iteration immediately instead of waiting for the timeout to elapse.
Currently waiting for the timeout is not so bad since it's only 10 seconds, but if I change it to exponential backoff, then suddenly the timeout can be very long. Hence my desire to interrupt the timeout and proceed straight to the next iteration.
Note: It is not imperative that my retrying loop follow the async-await pattern. It is OK if the waiting part is synchronous and blocking. I just want to be able to cancel the wait using a task completion source.