47 lines
1.9 KiB
C#
47 lines
1.9 KiB
C#
|
||
#if !DISABLE_PLAYFABCLIENT_API && !DISABLE_PLAYFAB_STATIC_API
|
||
using System;
|
||
using System.Threading.Tasks;
|
||
using UnityEngine;
|
||
|
||
namespace asap.playfab.async
|
||
{
|
||
public static partial class PlayFabClientAsyncAPI
|
||
{
|
||
/// <summary>
|
||
/// 通用重试封装,将任意返回 Task<T> 的 PlayFab API 调用包裹在重试逻辑中。
|
||
/// 当 API 调用返回 null(即发生错误)时触发重试,采用指数退避策略。
|
||
/// </summary>
|
||
/// <typeparam name="T">API 返回结果类型</typeparam>
|
||
/// <param name="apiCall">要执行的 API 调用,形如 () => PlayFabClientAsyncAPI.XxxAsync(request)</param>
|
||
/// <param name="maxRetries">最大重试次数,默认 3 次</param>
|
||
/// <param name="retryDelaySeconds">首次重试等待秒数,每次重试翻倍(指数退避),默认 1 秒</param>
|
||
/// <returns>成功时返回结果对象,所有重试均失败后返回 null</returns>
|
||
public static async Task<T> ExecuteWithRetryAsync<T>(
|
||
Func<Task<T>> apiCall,
|
||
int maxRetries = 3,
|
||
float retryDelaySeconds = 1f) where T : class
|
||
{
|
||
var attempts = 0;
|
||
while (true)
|
||
{
|
||
var result = await apiCall();
|
||
if (result != null)
|
||
return result;
|
||
|
||
if (attempts >= maxRetries)
|
||
{
|
||
Debug.LogWarning($"[PlayFabRetry] 已达到最大重试次数 {maxRetries},放弃重试。");
|
||
return null;
|
||
}
|
||
|
||
var delaySeconds = retryDelaySeconds * Mathf.Pow(2f, attempts);
|
||
Debug.LogWarning($"[PlayFabRetry] 第 {attempts + 1} 次重试,等待 {delaySeconds:F1} 秒后重试...");
|
||
await Task.Delay(TimeSpan.FromSeconds(delaySeconds));
|
||
attempts++;
|
||
}
|
||
}
|
||
}
|
||
}
|
||
#endif
|