最近写的一个 .NET Core 爬虫里用到了需要多次重试的功能,本着无脑输出的精神,google 了一下,还真给我找到了:
public static T Retry<T, TException>(int timesToRetry, Func<int, T> thingToTry) where TException : Exception { // Start at 1 instead of 0 to allow for final attempt int i; for (i = 1; i < timesToRetry; i++) { try { return thingToTry(i); } catch (TException) { // Maybe: Trace.WriteLine("Failed attempt..."); } } return thingToTry(i); // Final attempt, let exception bubble up } //这里我增加了个异步版本 public static async Task<T> RetryAsync<T, TException>(int timesToRetry, Func<int, Task<T>> thingToTry) where TException : Exception { // Start at 1 instead of 0 to allow for final attempt int i; for (i = 1; i < timesToRetry; i++) { try { return await thingToTry(i); } catch (TException) { // Maybe: Trace.WriteLine("Failed attempt..."); } } return await thingToTry(i); // Final attempt, let exception bubble up }
用法就很简单了:
using static AStaticClass; class A { void B() { //重试 3 次 var result = Retry<int, Exception>(3, nTimes => { //这里做需要重试的事情 Console.WriteLine($"第 {nTimes} 次尝试"); return 99999; }); } }
可惜当时看到的时候顺手关了浏览器,找不到原始出处了,等我找回来补上。
时间: 2024-10-20 03:42:49