【问题标题】:Checking the throttle before using a GraphServiceClient在使用 GraphServiceClient 之前检查油门
【发布时间】: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


    【解决方案1】:

    我相信您可以使用 Graph Developer 代理来测试这些。

    Microsoft Graph Developer Proxy 旨在提供一种更好的方法来测试使用 Microsoft Graph 的应用程序。使用代理来模拟错误、模拟响应和演示节流等行为,开发人员可以在代码投入生产之前在开发周期的早期识别并修复代码中的问题。

    可以在这里找到更多详细信息https://github.com/microsoftgraph/msgraph-developer-proxy

    【讨论】:

      猜你喜欢
      • 2021-06-26
      • 1970-01-01
      • 2021-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-22
      • 2021-07-28
      • 2019-03-16
      相关资源
      最近更新 更多