如何使用带有ExecuteQueryWithRetry的CSOM按名称(标题)获取SharePoint内容类型



我们在继承的Windows窗体应用程序中使用CSOM将文档批量上传到SharePoint,但我们一直受到限制(429个例外(。

我们根据这里的建议装饰了我们的http流量:

https://learn.microsoft.com/en-us/sharepoint/dev/general-development/how-to-avoid-getting-throttled-or-blocked-in-sharepoint-online#csom-增量测量扩展方法中的代码示例执行设备

我们还从客户端上下文扩展实现了ExecuteQueryWithRetry

https://learn.microsoft.com/en-us/dotnet/api/microsoft.sharepoint.client.clientcontextextensions.executequeryretry?view=sharepoint-pnpcoreol-3.2810

我们的部分代码使用此建议获得内容类型,但仍有429个例外:

https://sharepoint.stackexchange.com/questions/115499/get-a-content-type-by-name-title-using-csom

问题是,我该如何更换

ctx.ExecuteQuery();

ctx.ExecuteQueryWithRetry(10,30000);

CCD_ 2不存在于CCD_ 3的上下文中。

非常感谢。

看起来CSOM没有ExecuteQueryWithRetry扩展,但编写自己的扩展应该很容易。

public static class ClientContextExtensions
{
public static void ExecuteQueryWithRetry(this ClientRuntimeContext clientContext, int retryCount, int delayTimeMs)
{
var attemptCount = 0;
if (retryCount <= 0)
{
throw new ArgumentOutOfRangeException(nameof(retryCount));
}
if (delayTimeMs <= 0)
{
throw new ArgumentOutOfRangeException(nameof(delayTimeMs));
}
while (attemptCount <= retryCount)
{
try
{
clientContext.ExecuteQuery();
return;
}
catch (WebException wex)
{
if (wex.Response is HttpWebResponse response 
&& (response.StatusCode == HttpStatusCode.TooManyRequests 
|| response.StatusCode == HttpStatusCode.ServiceUnavailable))
{
// try read Retry-After header from the response
var retryAfterRaw = wex.Response.Headers[HttpResponseHeader.RetryAfter];
if (int.TryParse(retryAfterRaw, out var retryAfterSeconds))
{
Thread.Sleep(retryAfterSeconds * 1000);
}
// otherwise use defined delay
else
{
Thread.Sleep(delayTimeMs);
}
attemptCount++;
}
else
{
throw;
}
}
}
throw new Exception(string.Format("Maximum retry attempts {0} exceeded.", retryCount));
}
}

使用

ctx.ExecuteQueryWithRetry(10, 30000);

ContentTypeExtensions.GetByName内部

public static class ContentTypeExtensions
{
public static ContentType GetByName(this ContentTypeCollection cts, string name)
{
var ctx = cts.Context;
ctx.Load(cts);
ctx.ExecuteQueryWithRetry(10, 30000);
return Enumerable.FirstOrDefault(cts, ct => ct.Name == name);
}
}

最新更新