Skip to content

Instantly share code, notes, and snippets.

@zplume
Last active February 12, 2018 18:06
Show Gist options
  • Save zplume/cfb7bd17728bdf075c2d2d059c2633c6 to your computer and use it in GitHub Desktop.
Save zplume/cfb7bd17728bdf075c2d2d059c2633c6 to your computer and use it in GitHub Desktop.
using Microsoft.SharePoint.Client;
using System;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using static Microsoft.SharePoint.Client.ClientContextExtensions;
public static class ClientContextExtensions
{
public static async Task ExecuteQueryRetryAsync(this ClientContext clientContext,
CancellationTokenSource cancellationTokenSource, int retryCount = 3, int backoffDelaySeconds = 30)
{
if (retryCount <= 0)
throw new ArgumentException("Provide a retryCount value greater than zero.");
if (backoffDelaySeconds <= 0)
throw new ArgumentException("Provide a backoffDelaySeconds value greater than zero.");
int retryAttempts = 0;
while(retryAttempts < retryCount)
{
try
{
await clientContext.ExecuteQueryAsync().ConfigureAwait(false);
return;
}
catch (WebException w)
{
var response = w.Response as HttpWebResponse;
if (response != null && response.StatusCode == (HttpStatusCode)429)
{
Console.WriteLine($"CSOM request exceeded usage limits. Sleeping for {backoffDelaySeconds} seconds before retrying.");
await Task.Delay(backoffDelaySeconds * 1000);
// Add to retry count and increase delay.
retryAttempts++;
backoffDelaySeconds = backoffDelaySeconds * 2;
}
else
{
throw;
}
}
}
if (cancellationTokenSource != null)
{
// cancel tasks associated with the cancellation token source
cancellationTokenSource.Cancel();
}
throw new MaximumRetryAttemptedException($"CSOM request exceeded usage limits. Maximum ({retryCount}) retries unsuccessful, aborting.");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment