I have a send email method with a foreach, like this:
static void Main(string[] args)
{
foreach(var user in GetAllUsers())
{
SendMail(user.Email);
}
}
I need to improve that method. Using a multithread, because i dont want to wait the SendMail method executes each time for each user. Any sugestions to do that? Thanks
ForEach loop works like a Parallel. For loop. The loop partitions the source collection and schedules the work on multiple threads based on the system environment. The more processors on the system, the faster the parallel method runs.
The execution of Parallel. Foreach is faster than normal ForEach.
The short answer is no, you should not just use Parallel. ForEach or related constructs on each loop that you can. Parallel has some overhead, which is not justified in loops with few, fast iterations. Also, break is significantly more complex inside these loops.
Parallel. ForEach uses managed thread pool to schedule parallel actions. The number of threads is set by ThreadPool.
Try using a parallel foreach. I.e.
Parallel.ForEach(GetAllUsers(), user=>
{
SendMail(user.Email);
});
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