I have a Parallel.ForEach() async loop with which I download some webpages. My bandwidth is limited so I can download only x pages per time but Parallel.ForEach executes whole list of desired webpages.
Is there a way to limit thread number or any other limiter while running Parallel.ForEach?
Demo code:
Parallel.ForEach(listOfWebpages, webpage => {
Download(webpage);
});
The real task has nothing to do with webpages, so creative web crawling solutions won't help.
You can specify a
MaxDegreeOfParallelism
in aParallelOptions
parameter:MSDN: Parallel.ForEach
MSDN: ParallelOptions.MaxDegreeOfParallelism
You can use ParallelOptions and set MaxDegreeOfParallelism to limit the number of concurrent threads :
And for the VB.net users (syntax is weird and difficult to find)...
Use another overload of
Parallel.Foreach
that takes aParallelOptions
instance, and setMaxDegreeOfParallelism
to limit how many instances execute in parallel.