【发布时间】:2022-12-31 15:18:49
【问题描述】:
我有几个GraphServiceClients,我正在使用它们从 Microsoft Graph API 检索信息。 GraphServiceClient 调用有限制。据我从this documentation了解到,你不能在10分钟的时间范围内调用超过10,000次的API并且你只能同时使用4个并发请求。检查我是否已达到最大限制的线程安全且有效的方法是什么?
我的实现
我想出了这个,但我不确定它是否真的是 Microsoft Graph 检查限制的方式。
public class ThrottledClient
{
private readonly TimeSpan _throttlePeriod;
private readonly int _throttleLimit;
public ThrottledClient(int throttleLimit, TimeSpan throttlePeriod)
{
_throttleLimit = throttleLimit;
_throttlePeriod = throttlePeriod;
}
private readonly ConcurrentQueue<DateTime> _requestTimes = new();
public required GraphServiceClient GraphClient { get; set; }
public async Task CheckThrottleAsync(CancellationToken cancellationToken)
{
_requestTimes.Enqueue(DateTime.UtcNow);
if(_requestTimes.Count > _throttleLimit)
{
Console.WriteLine($"Count limit, {DateTime.Now:HH:mm:ss}");
_requestTimes.TryDequeue(out var oldestRequestTime);
var timeRemaining = oldestRequestTime + _throttlePeriod - DateTime.UtcNow;
if(timeRemaining > TimeSpan.Zero)
{
Console.WriteLine($"Sleeping for {timeRemaining}");
await Task.Delay(timeRemaining, cancellationToken).ConfigureAwait(false);
Console.WriteLine($"Woke up, {DateTime.Now:HH:mm:ss}");
}
}
}
}
public class Engine
{
public async Task RunAsync()
{
var client = GetClient();
await client.CheckThrottleAsync(_cts.Token).ConfigureAwait(false);
await DoSomethingAsync(client.GraphClient).ConfigureAwait(false);
}
}
我可以想到其他使用方式,例如 lock 或 Semaphore 但同样,我不确定我是否正确考虑了这一点。
【问题讨论】:
标签: c# .net concurrency microsoft-graph-api microsoft-graph-sdks