使用Parallel.ForEach和amp;之间的主要区别是什么? Task.Factory.StartNew

时间:2016-06-29 00:22:40

标签: c# asp.net .net asp.net-mvc parallel-processing

我正在开发一个asp.net mvc-4 Web应用程序..但我不确定使用这两种方法在列表上进行迭代并启动WebClient()调用之间有什么区别: -

方法-1

Parallel.ForEach(photos,new ParallelOptions { MaxDegreeOfParallelism = 7 }, p =>
                            {
         ResourceAccountListInfo resourceAccountListInfo = new ResourceAccountListInfo();
         WebClient wc = new WebClient();               

         var json =  wc.DownloadString(p.url);
         resourceAccountListInfo = JsonConvert.DeserializeObject<ResourceAccountListInfo>(json);
         if (resourceAccountListInfo.operation.Details.CUSTOMFIELD.Count > 0)
                    {
                        List<CUSTOMFIELD> customfield = resourceAccountListInfo.operation.Details.CUSTOMFIELD.Where(a =>
                                 a.CUSTOMFIELDLABEL.ToLower() == "name"
                                ).ToList();
                        if (customfield.Count == 1)
                        {
                            PMresourcesOnly.Add(resourceAccountListInfo.operation.Details);

                        }

                    }
            //code goes here
                            });

方法-2

   foreach (Photo p in photos)
                        {
            Task.Factory.StartNew(() =>
                        {
            ResourceAccountListInfo resourceAccountListInfo = new ResourceAccountListInfo();
            WebClient wc = new WebClient();

            var json =  wc.DownloadString(p.url);
            resourceAccountListInfo = JsonConvert.DeserializeObject<ResourceAccountListInfo>(json);
                     if (resourceAccountListInfo.operation.Details.CUSTOMFIELD.Count > 0)
                    {
                        List<CUSTOMFIELD> customfield = resourceAccountListInfo.operation.Details.CUSTOMFIELD.Where(a =>
                                 a.CUSTOMFIELDLABEL.ToLower() == "name"
                                ).ToList();
                        if (customfield.Count == 1)
                        {
                            PMresourcesOnly.Add(resourceAccountListInfo.operation.Details);

                        }

                    }
            //code goes here
                                });
                        }

感谢

1 个答案:

答案 0 :(得分:1)

Parallel.ForEach为迭代集合提供了便利。 尽管可以在循环内调用Task.Factory.StartNew,但它没有内在的东西表明它将在循环中使用。你可能只是开始一项任务。

由于Parallel.ForEach假设 set 并行操作,因此它为您提供ParallelOptions,允许您指定该一个循环范围内的并发操作数。这很有用,因为在某些情况下我们可能不关心有多少并发操作,但在其他情况下我们可能会这样做。请查看this answer,其中介绍了如何使用Semaphore来限制并发任务的数量。设置MaxDegreeOfParallelism要比使用Semaphore容易得多。

此外,Parallel.ForEach会返回ParallelLoopResult,让您可以看到循环中的所有操作。要在一系列任务中获得相同的可见性,还需要做更多的工作。您也可以通过一次方法调用来停止循环,而不是停止多个任务。

相关问题