1

谁能用简单的语言向我解释为什么我在使用 foreach 时得到一个大约 65 k 的文件,而在使用 Parallel.ForEach 时得到一个超过 3 GB 的文件?

foreach 的代码:

// start node xml document
var logItems = new XElement("log", new XAttribute("start", DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss")));
var products = new ProductLogic().SelectProducts();
var productGroupLogic = new ProductGroupLogic();
var productOptionLogic = new ProductOptionLogic();
// loop through all products
foreach (var product in products)
{
    // is in a specific group
    var id = Convert.ToInt32(product["ProductID"]);
    var isInGroup = productGroupLogic.GetProductGroups(new int[] { id }.ToList(), groupId).Count > 0;
    // get product stock per option
    var productSizes = productOptionLogic.GetProductStockByProductId(id).ToList();
    // any stock available
    var stock = productSizes.Sum(ps => ps.Stock);
    var hasStock = stock > 0;
    // get webpage for this product
    var productUrl = string.Format(url, id);
    var htmlPage = Html.Page.GetWebPage(productUrl);
    // check if there is anything to log
    var addToLog = false;
    XElement sizeElements = null;
    // if has no stock or in group
    if (!hasStock || isInGroupNew)
    {
        // page shows => not ok => LOG!
        if (!htmlPage.NotFound) addToLog = true;
    }
    // if page is ok
    if (htmlPage.IsOk)
    {
        sizeElements = GetSizeElements(htmlPage.Html, productSizes);
        addToLog = sizeElements != null;
    }
    if (addToLog) logItems.Add(CreateElement(productUrl, htmlPage, stock, isInGroup, sizeElements));
}
// save
var xDocument = new XDocument(new XDeclaration("1.0", "utf-8", "yes"), new XElement("log", logItems));
xDocument.Save(fileName);

并行代码的使用是一个小改动,只是将 foreach 替换为 Parallel.ForEach:

// loop through all products
Parallel.ForEach(products, product =>
{
    ... code ...
};

GetSizeElements 和 CreateElements 方法都是静态的。

update1 我使用锁使 GetSizeElements 和 CreateElements 方法成为线程安全的,但也无济于事。

update2 我得到了解决问题的答案。这很好。但我想获得更多关于为什么这些代码创建一个比 foreach 解决方案大得多的文件的见解。我正在尝试更了解代码在使用线程时的工作方式。这样我可以获得更多的洞察力,并且我可以学会避免这些陷阱。

4

2 回答 2

2

One thing stands out:

if (addToLog) 
  logItems.Add(CreateElement(productUrl, htmlPage, stock, isInGroup, sizeElements));

logItems is not tread-safe. That could be your core problem but there are lots of other possibilities.

You have the output files, look for the differences.

于 2013-10-21T11:16:27.197 回答
1

尝试在 foreach 循环中定义以下参数。

var productGroupLogic = new ProductGroupLogic();
var productOptionLogic = new ProductOptionLogic();

我认为只有两个被并行 foreach 循环内的所有线程使用,结果不必要地相乘。

于 2013-10-21T11:30:38.827 回答