弹性基础:重试与退避
使用指数退避和抖动实现简单重试;区分暂时性错误与致命错误;限制延迟上限;在取消时停止。
弹性基础:重试与退避 是 CoddyKit 上的免费 C# Academy 课时。 这是第 3 节课,共 3 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 C# Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 C# Academy 课程共包含 3 节课。
为什么要重试并使用退避
目标:提高调用的可靠性。
- 重试瞬时性失败
- 使用指数退避和抖动
- 设置最大尝试次数和最大延迟
- 遇到致命错误或取消时停止
对失败进行分类
瞬时性失败:超时、429/5xx、暂时性的网络故障。
致命失败:无效请求、未授权、验证错误——不要重试。
规则:只重试稍后可能成功的操作。
退避辅助方法
一个小型辅助方法会逐次增加延迟,并加入少量抖动;同时还会限制最大延迟。
using System;
using System.Threading;
using System.Threading.Tasks;
public static class Backoff
{
// Compute delay = min(base * 2^attempt, cap) + jitter
public static int ComputeDelayMs(int attempt, int baseMs, int capMs, int jitterMs, Random rng)
{
long exp = (long)baseMs << attempt; // base * 2^attempt
if (exp > capMs) exp = capMs;
int jitter = rng.Next(0, jitterMs + 1); // [0..jitterMs]
return (int)exp + jitter;
}
}
public class Program
{
public static void Main(string[] args)
{
Random rng = new Random(123);
for (int i = 0; i < 5; i++)
{
int d = Backoff.ComputeDelayMs(i, 100, 2000, 50, rng);
Console.WriteLine("Attempt " + i + " -> " + d + " ms");
}
}
}
重试包装器
包装调用:仅在出现瞬时性异常时重试,其他异常则停止。每次重试都会等待更长时间,并加入抖动。
using System;
using System.Threading;
using System.Threading.Tasks;
public class Program
{
static readonly Random Rng = new Random();
// Simulate an operation that sometimes fails transiently.
static async Task<string> FlakyAsync()
{
await Task.Delay(60);
// 50% chance of transient failure
if (DateTime.UtcNow.Ticks % 2 == 0) throw new TimeoutException("Transient");
return "OK";
}
static async Task<T> RetryAsync<T>(Func<Task<T>> action, int maxAttempts)
{
int baseMs = 100, capMs = 2000, jitterMs = 50;
for (int attempt = 0; attempt < maxAttempts; attempt++)
{
try
{
return await action();
}
catch (TimeoutException)
{
if (attempt == maxAttempts - 1) throw; // out of retries
int delay = Backoff.ComputeDelayMs(attempt, baseMs, capMs, jitterMs, Rng);
await Task.Delay(delay);
}
catch (Exception)
{
// Non-transient (unknown) -> do not retry
throw;
}
}
throw new InvalidOperationException("Unreachable");
}
public static void Main(string[] args)
{
try
{
string s = RetryAsync(FlakyAsync, 5).GetAwaiter().GetResult();
Console.WriteLine("Result: " + s);
}
catch (Exception ex)
{
Console.WriteLine("Failed: " + ex.GetType().Name);
}
}
}
有预算的重试
通过取消添加全局预算:将令牌同时传递给操作和退避延迟。
using System;
using System.Threading;
using System.Threading.Tasks;
public static class RetryUtil
{
static readonly Random Rng = new Random();
public static async Task<T> RetryAsync<T>(Func<CancellationToken, Task<T>> action, int maxAttempts, CancellationToken ct)
{
int baseMs = 100, capMs = 1500, jitterMs = 50;
for (int attempt = 0; attempt < maxAttempts; attempt++)
{
ct.ThrowIfCancellationRequested();
try
{
return await action(ct);
}
catch (TimeoutException)
{
if (attempt == maxAttempts - 1) throw;
int delay = Backoff.ComputeDelayMs(attempt, baseMs, capMs, jitterMs, Rng);
await Task.Delay(delay, ct); // pass token so we can abort waiting
}
}
throw new InvalidOperationException("Unreachable");
}
}
public class Program
{
static async Task<string> SometimesSlowAsync(CancellationToken ct)
{
await Task.Delay(200, ct);
if (DateTime.UtcNow.Millisecond % 3 != 0) throw new TimeoutException("Transient");
return "OK";
}
public static void Main(string[] args)
{
var cts = new CancellationTokenSource();
cts.CancelAfter(800); // overall budget
try
{
string s = RetryUtil.RetryAsync(SometimesSlowAsync, 5, cts.Token).GetAwaiter().GetResult();
Console.WriteLine("Done: " + s);
}
catch (OperationCanceledException) { Console.WriteLine("Canceled"); }
catch (Exception ex) { Console.WriteLine("Failed: " + ex.Message); }
}
}
指南
提示:
- 仅重试幂等调用。
- 为尝试次数和延迟设置上限。
- 加入少量抖动,避免惊群效应。
- 记录最终失败、失败原因和尝试次数。
退避定义
回顾
回顾:仅重试瞬时性错误,使延迟按指数增长并设置上限,加入抖动,并在取消或出现致命错误时停止。
常见问题解答
「弹性基础:重试与退避」课时是免费的吗?
是的 — 「弹性基础:重试与退避」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 C# Academy 课程的其余内容,请升级到 CoddyKit PRO。 C# Academy 课程共包含 3 节课。
「弹性基础:重试与退避」这节课中我会学到什么?
使用指数退避和抖动实现简单重试;区分暂时性错误与致命错误;限制延迟上限;在取消时停止。 你通过在浏览器中直接运行的动手代码来练习 C# Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 C# Academy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 C# Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 3 节。
「弹性基础:重试与退避」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 C# Academy 课中编写并运行代码吗?
能。每节 C# Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。