Last active
January 18, 2016 10:18
-
-
Save AzimUddin/d0613cbb6f852a57e05d to your computer and use it in GitHub Desktop.
Azure DocumentDB .Net SDK example of executing an Async method with retry to handle RequestRateTooLargeException or HTTP 429 errors
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <summary> | |
/// Execute the function with retries on throttle | |
/// </summary> | |
/// <typeparam name="V"></typeparam> | |
/// <param name="client"></param> | |
/// <param name="function"></param> | |
/// <returns></returns> | |
private static async Task<V> ExecuteWithRetries<V>(DocumentClient client, Func<Task<V>> function) | |
{ | |
TimeSpan sleepTime = TimeSpan.Zero; | |
while (true) | |
{ | |
try | |
{ | |
return await function(); | |
} | |
catch (DocumentClientException de) | |
{ | |
if ((int)de.StatusCode != 429) | |
{ | |
throw; | |
} | |
sleepTime = de.RetryAfter; | |
} | |
catch (AggregateException ae) | |
{ | |
if (!(ae.InnerException is DocumentClientException)) | |
{ | |
throw; | |
} | |
DocumentClientException de = (DocumentClientException)ae.InnerException; | |
if ((int)de.StatusCode != 429) | |
{ | |
throw; | |
} | |
sleepTime = de.RetryAfter; | |
} | |
await Task.Delay(sleepTime); | |
} | |
} | |
/// <summary> | |
/// Async method for inserting a single document, with retries | |
/// </summary> | |
/// <param name="student"></param> | |
/// <returns></returns> | |
private async Task InsertDocumentAsync(Student student) | |
{ | |
ResourceResponse<Document> response = await ExecuteWithRetries(client, () => client.CreateDocumentAsync(colSelfLink, student)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment