我有一个程序,我从Internet下载文件并处理它们。以下是我编写的使用线程下载文件的函数。
Task<File> re = Task.Factory.StartNew(() => { /*Download the File*/ });
re.ContinueWith((x) => { /*Do another function*/ });
我现在希望它只使用10个线程进行下载。我查看了 ParallelOptions.MaxDegreeOfParallelism 属性,但在任务返回结果时我无法理解如何使用它。
答案 0 :(得分:1)
您可以使用以下内容:
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 */ });
});
您的其他选择是使用PLINQ
或Paraller.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
});
当然,我不了解您的示例的背景,因此您可能需要根据您的要求进行调整。
答案 1 :(得分:1)
这样做的一个好方法是使用DataFlow API。要使用它,您必须安装Microsoft.Tpl.Dataflow Nuget package。
假设您有以下方法来下载和处理数据:
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.
}
假设您有一个要下载的网址列表:
List<string> urls = new List<string>();
然后,您可以使用DataFlow 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);
}