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/