c# - 是否可以使用 ConcurrentExclusiveSchedulerPair 优化这段代码?

标签 c# task-parallel-library

The problem is currently it runs pretty fine with limited number of reports (around 10 000), but on environments with much more reports it fails with Big amount of simultaneous requests for server causing heavy load on the server:

private void PerformSearch(SearchReportModel item)
{
    var tasks = new List<Task>();

    foreach (var term in item.SearchTerms)
    {
        var model = GetBaseQueryModel(item.Site);
        tasks.Add(Task.Factory.StartNew(() => CheckSearchTerm(model, term, item.Site, item.Language)));
    }
    try
    {
        Task.WaitAll(tasks.ToArray());
    }            
    catch (Exception ex)
    {
        Log4NetLogger.LogError(ex, ex.ToString());
        throw;
    }
}

最佳答案

假设 CheckSearchTerm 执行有问题的 API 调用,我建议仅使用 SemaphoreSlim限制负载:

Represents a lightweight alternative to Semaphore that limits the number of threads that can access a resource or pool of resources concurrently.

var tasks = new List<Task>();
var maximumRequests = 100; // maximum simultaneous invocations 
var limiter = new SemaphoreSlim(maximumRequests); // possibly make a global one via static variable or move inside of CheckSearchTerm
foreach (var term in item.SearchTerms)
{
    var model = GetBaseQueryModel(item.Site);
    tasks.Add(Task.Run(async () =>
    {
        await limiter.WaitAsync();
        try
        {
            CheckSearchTerm(model, term, item.Site, item.Language);
        }
        finally
        {
            limiter.Release();
        }
        
    }));
}

另一个选项是使用 Parallel.ForEach/PLINQParallelOptions.MaxDegreeOfParallelism/WithDegreeOfParallelism 设置为所需值。

关于c# - 是否可以使用 ConcurrentExclusiveSchedulerPair 优化这段代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72288254/

相关文章:

c# - 通用抽象类继承

c# - 为什么我的线程完成后要花这么长时间才能退出?

c# - 这是 TPL Dataflow 的工作吗?

c# - 是否有适用于 .NET 的声音 SDK?

c# - 如何将 HttpError 转换为 Exception 类型?

c# - C# 中的 const 和 readonly 有什么区别?

c# - 当我创建继承自 Form 的新类时,Visual Studio 会更改设计器生成的代码

c# - 如何将 HttpContext.Current 传递给在 .net 中使用 Parallel.Invoke() 调用的方法

c# - 在 TaskCompletionSource.Task(已调用 .SetResult)上调用 ContinueWith 方法是否安全?

c# - 一次启动多少个异步(非多线程)操作?这是可配置的吗?