MaxDegreeOfParallelism with Task.Factory.StartNew()

本文关键字:StartNew Factory with Task MaxDegreeOfParallelism | 更新日期: 2023-09-27 18:30:46

>我有一个程序,我可以从互联网上下载文件并处理它们。以下是我编写的用于使用线程下载文件的函数。

Task<File> re = Task.Factory.StartNew(() => { /*Download the File*/ });
re.ContinueWith((x) => { /*Do another function*/ });

我现在希望它只使用 10 个线程进行下载。我已经查看了ParallelOptions.MaxDegreeOfParallelism属性,但是当任务返回结果时,我不明白如何使用它。

MaxDegreeOfParallelism with Task.Factory.StartNew()

一个很好的方法是使用 DataFlow API。若要使用它,必须安装 Microsoft.Tpl.Dataflow Nuget 包。

假设您有以下下载和处理数据的方法:

public async Task<DownloadResult> DownloadFile(string url)
{
    //Asynchronously download the file and return the result of the download.
    //You don't need a thread to download the file if you use asynchronous API.
}
public ProcessingResult ProcessDownloadResult(DownloadResult download_result)
{
    //Synchronously process the download result and produce a ProcessingResult.    
}

假设您有一个要下载的 URL 列表:

List<string> urls = new List<string>();

然后,可以使用数据流 API 执行以下操作:

TransformBlock<string,DownloadResult> download_block =
    new TransformBlock<string, DownloadResult>(
        url => DownloadFile(url),
        new ExecutionDataflowBlockOptions
        {
            //Only 10 asynchronous download operations
            //can happen at any point in time.
            MaxDegreeOfParallelism = 10
        });
TransformBlock<DownloadResult, ProcessingResult> process_block =
    new TransformBlock<DownloadResult, ProcessingResult>(
        dr => ProcessDownloadResult(dr),
        new ExecutionDataflowBlockOptions
        {
            //We limit the number of CPU intensive operation
            //to the number of processors in the system.
            MaxDegreeOfParallelism = Environment.ProcessorCount
        });
download_block.LinkTo(process_block);
foreach(var url in urls)
{
    download_block.Post(url);
}

你可以使用如下的东西:

Func<File> work = () => {
    // Do something
    File file = ...
    return file
};
var maxNoOfWorkers = 10;    
IEnumerable<Task> tasks = Enumerable.Range(0, maxNoOfWorkers)
    .Select(s =>
    {
        var task = Task.Factory.StartNew<File>(work);
        return task.ContinueWith(ant => { /* do soemthing else */ });        
    });

通过这种方式,TPL决定从threadpool获取多少线程,但是如果您真的想创建一个专用(non-threadpool)线程,然后您可以使用:

IEnumerable<Task> tasks = Enumerable.Range(0, maxNoOfWorkers)
    .Select(s =>
    {
        var task = Task.Factory.StartNew<File>(
            work, 
            CancellationToken.None, 
            TaskCreationOptions.LongRunning, 
            TaskScheduler.Default);
        return task.ContinueWith(ant => { /* do soemthing else */ });
    });

您的其他选择是使用PLINQParaller.For/ForEach,您可以使用MaxDegreeOfParallelism

PLINQ示例可以是:

Func<File> work = () => {
    // Do something
    File file = ...
    return file
};
var maxNoOfWorkers = 10;
ParallelEnumerable.Range(0, maxNoOfWorkers)
    .WithDegreeOfParallelism(maxNoOfWorkers)
    .ForAll(x => { 
        var file = work();
        // Do something with file
    });

当然,我不知道您的示例的上下文,因此您可能需要根据自己的要求对其进行调整。