private async Task <string> GetStringAsync(string url) { return(await _requestRetryPolicy.ExecuteAsync(async() => { using (var request = new HttpRequestMessage(HttpMethod.Get, url)) using (var response = await InternalSendRequestAsync(request)) return await response.Content.ReadAsStringAsync(); })); }
/// <summary> /// Executes an asynchronous action with retry. /// </summary> public static Task ExecuteAsync(this IRetry retry, Func <Task> taskFunction) { retry.GuardNotNull(nameof(retry)); taskFunction.GuardNotNull(nameof(taskFunction)); // Execute return(retry.ExecuteAsync(taskFunction.ToObjectTaskFunc())); }
private async Task <JToken> GetApiResponseAsync(AuthToken token, string resource, string endpoint, params string[] parameters) { // Create retry policy IRetry retry = Retry.Create() .Catch <HttpErrorStatusCodeException>(false, e => (int)e.StatusCode >= 500) .Catch <HttpErrorStatusCodeException>(false, e => (int)e.StatusCode == 429) .WithMaxTryCount(7200) .WithDelay(TimeSpan.FromSeconds(0.5)); // Send request return(await retry.ExecuteAsync(async() => { // Create request const string apiRoot = "https://discordapp.com/api/v6"; using (HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, $"{apiRoot}/{resource}/{endpoint}")) { // Set authorization header request.Headers.Authorization = token.Type == AuthTokenType.Bot ? new AuthenticationHeaderValue("Bot", token.Value) : new AuthenticationHeaderValue(token.Value); // Add parameters foreach (string parameter in parameters) { string key = parameter.SubstringUntil("="); string value = parameter.SubstringAfter("="); // Skip empty values if (value.IsNullOrWhiteSpace()) { continue; } request.RequestUri = request.RequestUri.SetQueryParameter(key, value); } // Get response using (HttpResponseMessage response = await _httpClient.SendAsync(request)) { // Check status code // We throw our own exception here because default one doesn't have status code if (!response.IsSuccessStatusCode) { throw new HttpErrorStatusCodeException(response.StatusCode, response.ReasonPhrase); } // Get content string raw = await response.Content.ReadAsStringAsync(); // Parse return JToken.Parse(raw); } } })); }
public static async Task ExecuteAsync(this IRetry retry, Func <CancellationToken, Task> body) { await retry.ExecuteAsync <object>(cancellationToken => { body(cancellationToken); return(null); }, CancellationToken.None); }
public static void Execute(this IRetry retry, Action body) { retry.ExecuteAsync(_ => { body(); return(Task.FromResult <object>(null)); }, CancellationToken.None).GetAwaiter().GetResult(); }
public static T Execute <T>(this IRetry retry, Func <T> body) { return(retry.ExecuteAsync(_ => Task.FromResult(body()), CancellationToken.None).GetAwaiter().GetResult()); }