做多线程foreach循环最好的方法 [英] Best way to do a multithread foreach loop

查看:98
本文介绍了做多线程foreach循环最好的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个发送电子邮件的方法在foreach,像这样的:

I have a send email method with a foreach, like this:

static void Main(string[] args)
{
   foreach(var user in GetAllUsers())
   {
      SendMail(user.Email);
   }
}



我需要改进该方法。使用多线程的,因为我不想等到sendmail的方法执行为每个用户每次。
任何sugestions这样做呢?
谢谢

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。即

Try using a parallel foreach. I.e.

Parallel.ForEach(GetAllUsers(), user=>
{
  SendMail(user.Email);
});

这篇关于做多线程foreach循环最好的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆