繁体   English   中英

C# - Parallel.Foreach() 用于服务调用

[英]C# - Parallel.Foreach() for Service Call

我有一个控制台应用程序,它执行下面提到的 3 个步骤,

  1. 从 db 获取待处理的通知记录
  2. 调用服务发送 email(服务返回 email 地址作为响应)
  3. 得到服务响应后,更新数据库

对于第 2 步,我使用的是Parallel.Foreach() ,它的效果比foreach()好得多。 我已经阅读了很多关于 stackoverflow 的文章和线程,这在这个主题上造成了更多的混乱。 我有几个问题

  1. 我在服务器上运行它,它会影响性能吗?我应该限制线程数吗? (email 计数可以是 0-500 或 1000)
  2. 我遇到了一个问题,在第 2 步中,服务返回了 email 地址作为响应,但在更新数据库时它不可用。 (这里的电子邮件计数是 400)我怀疑问题可能是因为使用了 parallel.foreach 并且它没有添加到notifList中。 如果是这种情况,我可以在 Parallel.Foreach() 循环结束后添加 Thread.Sleep(1000) 吗,它可以解决问题吗?
  3. 如果出现任何异常,我应该明确取消线程吗?

感谢您花时间和精力帮助我。 谢谢!

public void notificationMethod()
{
    List<notify> notifList = new List<notify>();

    //step 1
    List<orders> orderList = GetNotifs();

    try
    {
        if (orderList.Count > 0)
        {
            Parallel.ForEach(orderList, (orderItem) =>
            {
               //step 2
               SendNotifs(orderItem);
                notifList.Add(new notify()
               {
                   //building list by adding email address along with other information
               });
            });
            if (notifList.Count > 0)
            {
                int index = 0; 
                int rows = 10; 
                int skipRows = index * rows;
                int updatedRows = 0;
                while (skipRows < notifList.Count)
                {
                    //pagination 
                    List<notify> subitem = notifList.Skip(index * rows).Take(rows).ToList<notify>();
                    updatedRows += subitem.Count;

                    //step 3
                    UpdateDatabase(subitem);

                    index++;
                    skipRows = index * rows;
                }
            }
        }
    }
    catch (ApplicationException ex)
    {
    }            
}


关于使用Parallel.ForEach()是否有助于提高性能,我也有类似的情况。 但是当我看到下面来自微软的视频时,它让我想到了 select Parallel.ForEach()适用于 CPU 密集型工作负载。 在这种情况下,您的场景将属于 I/O 密集型工作负载,并且可以通过async / await更好地处理。

https://channel9.msdn.com/Series/Three-Essential-Tips-for-Async/Tip-2-Distinguish-CPU-Bound-work-from-IO-bound-work

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM