I have a for loop that spawns threads… I want it to spawn 5 threads then wait until it drops down to 4 then spawn another one.
Basically, if I have 100 records, I want to to process 5 at a time. Which is the preferred approach?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The preferred approach would probably be to just use one of the built-in mechanisms for this.
For example,
Parallel.ForEachhas the option of specifying the MaxDegreeOfParallelism to use, which corresponds to the maximum number of threads used.This would let you just write something like:
If you’re “record processing” is a mapping or query operation, another good option is to use PLINQ’s WithDegreeOfParallelism to limit the parallelism:
I would choose the first option if you’re just “processing” each record (ie: ProcessRecord is a void method), and the second if you’re doing some type of mapping operation or query over the records, and returning results from the record processing.