相关疑难解决方法(0)

如何限制通过并行任务库运行的活动任务的数量?

我有一些包含Action(System.Action)的ConcurrentQueue.需要运行此队列中的每个操作(需要使用invoke调用).

当队列不为空时=>需要调用动作=>但是我想对将要运行的并行任务的数量进行一些限制.除此之外,可以随时向队列添加新动作.

怎么做 ?

(使用.net 4.0)

我写了一些东西,但我不确定这是最好的方法

 SemaphoreSlim maxThread = new SemaphoreSlim(5);

 while( !actionQueue.IsEmpty )
        {
            maxThread.Wait();
            Task.Factory.StartNew( () =>
            {
                Action action;
                if( actionExecution.TryDequeue( out action) )
                {
                    action.Invoke();
                }
            },
            TaskCreationOptions.LongRunning ).ContinueWith( ( task ) => maxThread.Release() );
        }
    }
Run Code Online (Sandbox Code Playgroud)

c# task-parallel-library

8
推荐指数
1
解决办法
4363
查看次数

如何限制.Net Core Web API中并发的外部API调用?

目前我正在开发一个 .net core Web api 项目,该项目从外部 Web api 获取数据。它们的末端有一个 25 的并发速率限制器(允许 25 个并发 api 调用)。第 26 个 API 调用将失败。

因此,我想在我的 Web API 项目上实现并发 API 速率限制器,并且需要跟踪失败的第 26 个 API 调用,并且需要重试(可能是 get 或 post 调用)。我的 api 代码中有多个 get 请求和 post 请求

以下是我的 Web api 中的 httpservice.cs

public HttpClient GetHttpClient()
{
    HttpClient client = new HttpClient
    {
        BaseAddress = new Uri(APIServer),
    };
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    client.DefaultRequestHeaders.Add("Authorization", ("Bearer " + Access_Token));
    return client;
}
private HttpClient Client;
public async Task<Object> Get(string apiEndpoint)
{

    Client = …
Run Code Online (Sandbox Code Playgroud)

c# concurrency semaphore asp.net-web-api asp.net-core-webapi

5
推荐指数
1
解决办法
5161
查看次数

分区:如何在每个分区后添加等待

我有一个每分钟接受 20 个请求的 API,之后我需要等待 1 分钟才能查询它。我有一个项目列表(通常超过 1000 个),我需要从 API 查询其详细信息,我的想法是我可以用来将Partitioner我的列表划分为 20 个项目/请求,但很快我意识到这Partitioner不起作用,我的第二个想法在分区中添加 adelay但这也是一个坏主意,根据我的理解,它会在每个不需要的请求之后添加一个延迟,相反,我需要在每个Partition. 下面是我的代码:

public static async Task<IEnumerable<V>> ForEachAsync<T, V>(this IEnumerable<T> source,
    int degreeOfParallelism, Func<T, Task<V>> body, CancellationToken token,
    [Optional] int delay)
{
    var whenAll = await Task.WhenAll(
        from partition in Partitioner.Create(source).GetPartitions(degreeOfParallelism)
        select Task.Run(async delegate {
            var allResponses = new List<V>();
            using (partition)
                while (partition.MoveNext())
                {
                    allResponses.Add(await body(partition.Current));
                    await Task.Delay(TimeSpan.FromSeconds(delay));
                }
            return allResponses;
        }, token));
    return whenAll.SelectMany(x => x);
}
Run Code Online (Sandbox Code Playgroud)

有谁知道我怎样才能做到这一点?

c# parallel-processing rate-limiting task-parallel-library

1
推荐指数
1
解决办法
1051
查看次数