【发布时间】:2016-10-31 11:56:18
【问题描述】:
我正在开发一个 asp.net mvc-4 Web 应用程序。但我不确定使用这两种方法对列表进行迭代和启动 WebClient() 调用之间有什么区别:-
方法一
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
});
}
谢谢
【问题讨论】:
-
所有线程都替换
resourceAccountListInfo吗?这似乎是错误的 -
不同之处在于: Parallel.ForEach 等到所有“照片”完成,然后继续。在 Task.Factory.StartNew 中,无论照片是否完成,它始终会继续。
-
@ScottChamberlain 抱歉,我只显示了与我的问题相关的部分代码。现在每次迭代中的 resourceAccountListInfo 都有额外的处理......
-
最终,您可以根据自己的需要为您的代码选择最佳解决方案;我想总是很难确定什么是最合适的,所以你需要根据不同的解决方案如何工作来定义它,所以它需要一些试验和错误,以及性能指标,并且必须检查哪个是最合适的我认为最好的 :) 我只是想给我的两分钱!
-
@johnG 有很多方法可以让代码做同样的事情,我不认为你可以概括地说 Parallel.ForEach 比 Task.WhenAll 差,反之亦然 except 在某些情况下......即使在那些情况下,它们可能无论如何都会有相同的最终结果,所以这并不重要。在性能方面可能很重要。您应该在运行时在任务管理器中查看您的 CPU 核心使用情况,看看您是否正在使用所有 CPU 可计算性。
标签: c# asp.net .net asp.net-mvc parallel-processing