c# - 任务.WaitSubset/任务.WaitN?

标签 c# multithreading task-parallel-library task

Task.WaitAll 方法等待所有任务,Task.WaitAny 方法等待一个任务。如何等待任意N个任务?

用例:下载搜索结果页面,每个结果都需要一个单独的任务来下载和处理。如果我使用 WaitAll 在获取下一个搜索结果页面之前等待子任务的结果,我将不会使用所有可用资源(一个长任务会延迟其余的)。根本不等待会导致数千个任务排队,这也不是最好的主意。

那么,如何等待任务子集完成呢?或者,如何等待任务调度队列只有 N 个任务?

最佳答案

对于 TPL 数据流来说,这看起来是一个很好的问题,它将允许您控制并行性和缓冲以最大速度进行处理。

这里有一些(未经测试的)代码向您展示我的意思:

static void Process()
{
    var searchReader =
        new TransformManyBlock<SearchResult, SearchResult>(async uri =>
    {
        // return a list of search results at uri.

        return new[]
        {
            new SearchResult
            {
                IsResult = true,
                Uri = "http://foo.com"
            },
            new SearchResult
            {
                // return the next search result page here.
                IsResult = false,
                Uri = "http://google.com/next"
            }
        };
    }, new ExecutionDataflowBlockOptions
    {
        BoundedCapacity = 8, // restrict buffer size.
        MaxDegreeOfParallelism = 4 // control parallelism.
    });

    // link "next" pages back to the searchReader.
    searchReader.LinkTo(searchReader, x => !x.IsResult);

    var resultActor = new ActionBlock<SearchResult>(async uri =>
    {
        // do something with the search result.
    }, new ExecutionDataflowBlockOptions
    {
        BoundedCapacity = 64,
        MaxDegreeOfParallelism = 16
    });

    // link search results into resultActor.
    searchReader.LinkTo(resultActor, x => x.IsResult);

    // put in the first piece of input.
    searchReader.Post(new SearchResult { Uri = "http://google/first" });
}

struct SearchResult
{
    public bool IsResult { get; set; }
    public string Uri { get; set; }
}

关于c# - 任务.WaitSubset/任务.WaitN?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21666797/

相关文章:

c# - 允许任何用户在没有凭据的情况下访问 'signalr/hubs',使用 cors(服务器运行 windows 身份验证)

android - 实时示例和 AIDL 在 android 中的使用?

java - Java并发性–立即关闭线程池

c# - 使用 async/await 并从 ASP.NET Web API 方法返回 Task<HttpResponseMessage>

c# - 为什么属性中的异步/等待方法永远不会返回

c# - for 循环和 Parallel.For() 之间的性能损失(MaxDegreeOfParallelism 为 1)

c# - Windows 10 支持的操作系统 GUID 是什么?

c# - 如何使用 C# 从 SqlConnection 返回多个结果

c# - RazorView,对多个模板使用相同的模型对象

c# - 多核文本文件解析