Closed monotore closed 8 years ago
Could you please provide a sample of what you're trying to accomplish?
I have a class where the Policy is a field. The field is used by multiple methods of the class. An instance of the class is used by multiple threads at the same time. Is this OK?
public class Class
{
private readonly Policy _policy = Policy
.Handle<TimeoutException>()
.RetryForever();
public void MethodA()
{
_policy.Execute(DoSomething);
}
public void MethodB()
{
_policy.Execute(DoSomething);
}
}
@monotore @joelhulen My reading of the Polly codebase is that Policy instances are thread-safe.
@joelhulen, your team might want to verify this for yourselves independently (see if you agree...), but my reasoning:
Retry policies: Use an underlying instance of IRetryPolicyState
to maintain retry state (eg number of retries made). However, each call to someRetryPolicyInstance.Execute(...)
uses the Func<IRetryPolicyState> policyStateFactory
to make a new, private instance of the relevant IRetryPolicyState
implementation, so retry state data for different calls through someRetryPolicyInstance.Execute(...)
is entirely independent (and hence thread-safe).
Circuit-breaker policies: Multiple calls to someCircuitBreakerPolicyInstance.Execute(...)
share (and must share) the same underlying ICircuitBreakerState
, so that any exceptions thrown during each call to Execute(...)
accumulate towards the (consecutive) total at which the circuit will break. However, all manipulation and reading of the ICircuitBreakerState
's state data is protected by locks making it thread-safe.
Hope this is useful.
New documentation of some example policy patterns has been added at https://github.com/App-vNext/Polly/wiki/Some-policy-patterns. This covers:
Can I share a Policy instance between threads, or should I create a new instance each time I run a policy?