c# - 嵌套线程排队

标签 c# .net multithreading

在我的程序中,产品(或成分)需要更新其自己的父级价格,而这些父级必须为其父级执行相同的操作,依此类推。

我写了一个这样的方法:

public static Price CalculatePrice(this IProduct pro)
{
    /// calculation stuff
}

private static SystemContext innerContext;

/// <summary>
/// In the main controller this method called for updates
/// </summary>
/// <param name="pro"></param>
/// <param name="sc"></param>
public static void UpdatePrice(this IProduct pro, ref SystemContext sc)
{
    if (sc.Relations.Where(t => t.SubProduct.ID == pro.ID).Any())
    {

        // If this returns any, this means there are some products using this product as their sub-product.
        var list = sc.Relations.Where(t => t.SubProduct.ID == pro.ID).ToList();

            ConcurrentQueue<Relation> quee = new ConcurrentQueue<Relation>(list);

            innerContext = new SystemContext();

            Task task = new Task(() => UpdatePrice(ref quee));
            task.Start();
    }
}


private static void UpdatePrice(ref ConcurrentQueue<Relation> queue)
{
    Relation val;

    while (queue.TryDequeue(out val))
    {
        val.Product.Price = val.Product.CalculatePrice();

        var list = innerContext.Relations.Where(t => t.SubProduct.ID == val.Product.ID);

        if (list.Any())
        {
            ConcurrentQueue<Relation> quee = new ConcurrentQueue<Relation>(list);
            Task task = new Task(() => UpdatePrice(ref quee));
            task.Start();

        }
    }
}

尽管第一级父产品已更新,但第二级未更新。

有更好的逻辑来做到这一点吗?

顺便说一句,任何最低级别的产品都有大约 1000 个父级(递归地)。这意味着耗时(因为价格的计算)。所以如果你在提供建议的时候也考虑一下时间那就完美了...

编辑

当我做一些测试时。我算了一下,一些最低级别的产品有 4000 个父级。

最佳答案

我认为解决方案可能是迭代地而不是递归地处理数据。您可以通过将您感兴趣的所有产品添加到列表中并在处理其中的产品时不断添加到该列表来实现此目的。

类似这样的事情:

public static void UpdatePrice(this IProduct pro, ref SystemContext sc)
{
    var relations = sc.Relations.Where(t => t.SubProduct.ID == pro.ID).ToList();

    for (int i = 0; i < relations.Count; i++)
    {
        relations[i].Product.Price = relations[i].Product.CalculatePrice();
        relations.AddRange(sc.Relations.Where(t => t.SubProduct.ID == relations[i].Product.ID)); 
    }    
}

关于c# - 嵌套线程排队,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27767801/

相关文章:

.net - 我如何订阅 MSMQ 队列但只有 "peek".Net 中的消息?

java - 单例类中的方法是线程安全的吗?

c# - 在 try block 中重新抛出异常 c#

c# - 跨线程操作无效 : Control accessed from a thread other than the thread it was created on

.net - 使用 jsonp 和基于 SSL/HTTPS 的 .NET Web 服务进行跨域 AJAX

c# - Autofac 为新线程创建子范围未按预期工作 "Instances cannot be resolved and nested lifetimes cannot be created..."

python - pyinotify asyncnotifier 线程问题

java - 使用多个线程是不好的做法吗? (通过 SwingWorkers)

c# - 在C#中产生两个列表项的集合差异

c# - Response.Redirect 给出 HttpException 异常