Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to do a multithread foreach loop [closed]

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

like image 935
gog Avatar asked Oct 23 '13 11:10

gog


People also ask

Is ForEach multithreaded?

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.

Which is faster parallel ForEach or ForEach?

The execution of Parallel. Foreach is faster than normal ForEach.

Should you use parallel 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.

Does parallel ForEach use ThreadPool?

Parallel. ForEach uses managed thread pool to schedule parallel actions. The number of threads is set by ThreadPool.


1 Answers

Try using a parallel foreach. I.e.

Parallel.ForEach(GetAllUsers(), user=>
{
  SendMail(user.Email);
});
like image 150
Mike Norgate Avatar answered Sep 22 '22 10:09

Mike Norgate