在我的程序中,产品(或成分)需要更新其自己的父级价格,而这些父级必须为其父级执行相同的操作,依此类推。
我写了一个这样的方法:
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/