I am trying to understand how Parallelism is implemented in .Net. Following code is taken as an example from Reed Copsey Blog.
This code loops over the customers collection and sends them emails after 14 days since their last contact. My Question here is if the customer table is very BIG and sending an email takes few seconds, will NOT this code takes CPU in Denial of Services mode to other important processes?
Is there a way to run following lines of code in parallel but only using few cores so other processes can share CPU? Or Am i approaching the problem in wrong way?
Parallel.ForEach(customers, (customer, parallelLoopState) =>
{
// database operation
DateTime lastContact = theStore.GetLastContact(customer);
TimeSpan timeSinceContact = DateTime.Now - lastContact;
// If it's been more than two weeks, send an email, and update...
if (timeSinceContact.Days > 14)
{
// Exit gracefully if we fail to email, since this
// entire process can be repeated later without issue.
if (theStore.EmailCustomer(customer) == false)
parallelLoopState.Break();
else
customer.LastEmailContact = DateTime.Now;
}
});
Accepted Answer:
Thought Process was RIGHT! as Cole Campbell pointed out, One can control and configure how many cores should be used by specifying ParallelOption object in this specific example. Here is how.
var parallelOptions = new ParallelOptions();
parallelOptions.MaxDegreeOfParallelism =
Math.Max(Environment.ProcessorCount / 2, 1);
And Parallel.ForEach will be used as follow.
Parallel.ForEach(customers, parallelOptions,
(customer, parallelLoopState) =>
{
//do all same stuff
}
Same concept can be applied for PLINQ using .WithDegreeOfParallelism(int numberOfThreads). For more information on how to configure Parallel Options, read this.
The Task Parallelism Library is designed to take the system workload into account when scheduling tasks to run, so this shouldn't be an issue. However, you can use the MaxDegreeOfParallelism
property on the ParallelOptions
class, which can be passed into one of the overloads of ForEach()
, to restrict the number of concurrent operations that it can perform, if you really need to.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With