|
10 | 10 |
|
11 | 11 | --- |
12 | 12 |
|
| 13 | +The timeout resilience strategy cancels the execution if it does not complete within the specified timeout period. If the execution is canceled by the timeout strategy, it throws a `TimeoutRejectedException`. The timeout strategy operates by wrapping the incoming cancellation token with a new one. Should the original token be canceled, the timeout strategy will transparently honor the original cancellation token without throwing a `TimeoutRejectedException`. |
| 14 | + |
| 15 | +> ![IMPORTANT] |
| 16 | +> It is crucial that the user's callback respects the cancellation token. If it does not, the callback will continue executing even after a cancellation request, thereby ignoring the cancellation. |
| 17 | +
|
13 | 18 | ## Usage |
14 | 19 |
|
15 | 20 | <!-- snippet: timeout --> |
@@ -119,3 +124,47 @@ sequenceDiagram |
119 | 124 | T->>P: Throws <br/>TimeoutRejectedException |
120 | 125 | P->>C: Propagates exception |
121 | 126 | ``` |
| 127 | + |
| 128 | +## Anti-patterns |
| 129 | + |
| 130 | +### Ignoring Cancellation Token |
| 131 | + |
| 132 | +❌ DON'T |
| 133 | + |
| 134 | +Ignore the cancellation token provided by the resilience pipeline: |
| 135 | + |
| 136 | +<!-- snippet: timeout-ignore-cancellation-token --> |
| 137 | +```cs |
| 138 | +var pipeline = new ResiliencePipelineBuilder() |
| 139 | + .AddTimeout(TimeSpan.FromSeconds(1)) |
| 140 | + .Build(); |
| 141 | + |
| 142 | +await pipeline.ExecuteAsync( |
| 143 | + async innerToken => await Task.Delay(TimeSpan.FromSeconds(3), outerToken), // The delay call should use innerToken |
| 144 | + outerToken); |
| 145 | +``` |
| 146 | +<!-- endSnippet --> |
| 147 | + |
| 148 | +**Reasoning**: |
| 149 | + |
| 150 | +The provided callback ignores the `innerToken` passed from the pipeline and instead uses the `outerToken`. For this reason, the cancelled `innerToken` is ignored, and the callback is not cancelled within 1 second. |
| 151 | + |
| 152 | +✅ DO |
| 153 | + |
| 154 | +Respect the cancellation token provided by the pipeline: |
| 155 | + |
| 156 | +<!-- snippet: timeout-respect-cancellation-token --> |
| 157 | +```cs |
| 158 | +var pipeline = new ResiliencePipelineBuilder() |
| 159 | + .AddTimeout(TimeSpan.FromSeconds(1)) |
| 160 | + .Build(); |
| 161 | + |
| 162 | +await pipeline.ExecuteAsync( |
| 163 | + static async innerToken => await Task.Delay(TimeSpan.FromSeconds(3), innerToken), |
| 164 | + outerToken); |
| 165 | +``` |
| 166 | +<!-- endSnippet --> |
| 167 | + |
| 168 | +**Reasoning**: |
| 169 | + |
| 170 | +The provided callback respects the `innerToken` provided by the pipeline, and as a result, the callback is correctly cancelled by the timeout strategy after 1 second plus `TimeoutRejectedException` is thrown. |
0 commit comments