c# - 如何限制每秒对网络服务器的 HttpWebRequest 数量?

标签 c# httpwebrequest

在使用 HttpWebRequest 向一个应用程序服务器发出并行请求时,我需要实现一种限制机制(每秒请求数)。我的 C# 应用程序必须每秒向远程服务器发出不超过 80 个请求。远程服务管理员施加的限制不是硬限制,而是我的平台和他们的平台之间的“SLA”。

如何在使用 HttpWebRequest 时控制每秒的请求数?

最佳答案

我遇到了同样的问题,找不到现成的解决方案,所以我做了一个,就在这里。这个想法是使用 BlockingCollection<T>添加需要处理的项目,并使用 Reactive Extensions 订阅限速处理器。

Throttle 类是this rate limiter 的重命名版本

public static class BlockingCollectionExtensions
{
    // TODO: devise a way to avoid problems if collection gets too big (produced faster than consumed)
    public static IObservable<T> AsRateLimitedObservable<T>(this BlockingCollection<T> sequence, int items, TimeSpan timePeriod, CancellationToken producerToken)
    {
        Subject<T> subject = new Subject<T>();

        // this is a dummyToken just so we can recreate the TokenSource
        // which we will pass the proxy class so it can cancel the task
        // on disposal
        CancellationToken dummyToken = new CancellationToken();
        CancellationTokenSource tokenSource = CancellationTokenSource.CreateLinkedTokenSource(producerToken, dummyToken);

        var consumingTask = new Task(() =>
        {
            using (var throttle = new Throttle(items, timePeriod))
            {
                while (!sequence.IsCompleted)
                {
                    try
                    {
                        T item = sequence.Take(producerToken);
                        throttle.WaitToProceed();
                        try
                        {
                            subject.OnNext(item);
                        }
                        catch (Exception ex)
                        {
                            subject.OnError(ex);
                        }
                    }
                    catch (OperationCanceledException)
                    {
                        break;
                    }
                }
                subject.OnCompleted();
            }
        }, TaskCreationOptions.LongRunning);

        return new TaskAwareObservable<T>(subject, consumingTask, tokenSource);
    }

    private class TaskAwareObservable<T> : IObservable<T>, IDisposable
    {
        private readonly Task task;
        private readonly Subject<T> subject;
        private readonly CancellationTokenSource taskCancellationTokenSource;

        public TaskAwareObservable(Subject<T> subject, Task task, CancellationTokenSource tokenSource)
        {
            this.task = task;
            this.subject = subject;
            this.taskCancellationTokenSource = tokenSource;
        }

        public IDisposable Subscribe(IObserver<T> observer)
        {
            var disposable = subject.Subscribe(observer);
            if (task.Status == TaskStatus.Created)
                task.Start();
            return disposable;
        }

        public void Dispose()
        {
            // cancel consumption and wait task to finish
            taskCancellationTokenSource.Cancel();
            task.Wait();

            // dispose tokenSource and task
            taskCancellationTokenSource.Dispose();
            task.Dispose();

            // dispose subject
            subject.Dispose();
        }
    }
}

单元测试:

class BlockCollectionExtensionsTest
{
    [Fact]
    public void AsRateLimitedObservable()
    {
        const int maxItems = 1; // fix this to 1 to ease testing
        TimeSpan during = TimeSpan.FromSeconds(1);

        // populate collection
        int[] items = new[] { 1, 2, 3, 4 };
        BlockingCollection<int> collection = new BlockingCollection<int>();
        foreach (var i in items) collection.Add(i);
        collection.CompleteAdding();

        IObservable<int> observable = collection.AsRateLimitedObservable(maxItems, during, CancellationToken.None);
        BlockingCollection<int> processedItems = new BlockingCollection<int>();
        ManualResetEvent completed = new ManualResetEvent(false);
        DateTime last = DateTime.UtcNow;
        observable
            // this is so we'll receive exceptions
            .ObserveOn(new SynchronizationContext()) 
            .Subscribe(item =>
                {
                    if (item == 1)
                        last = DateTime.UtcNow;
                    else
                    {
                        TimeSpan diff = (DateTime.UtcNow - last);
                        last = DateTime.UtcNow;

                        Assert.InRange(diff.TotalMilliseconds,
                            during.TotalMilliseconds - 30,
                            during.TotalMilliseconds + 30);
                    }
                    processedItems.Add(item);
                },
                () => completed.Set()
            );
        completed.WaitOne();
        Assert.Equal(items, processedItems, new CollectionEqualityComparer<int>());
    }
}

关于c# - 如何限制每秒对网络服务器的 HttpWebRequest 数量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10257312/

相关文章:

c# - 在linq中获取多个不同的分组值

使用不安全代码的 C# 位图图像屏蔽

c# - HttpWebRequest 超时

c# - 获取本地照片 Windows Phone 8 模拟器

c# - 如何重新映射程序集版本

c# - 在 C# 中使用 TCPClient 和 NetworkStream 发送文件

java - 如果网页已更新,则发出警报

c# - 在 C# 中使用 HttpWebRequest 发布参数

c# - HttpWebResponse - 正确处理连接

json - WebRequest 缓存 Windows Phone 7