使用thread.join确保集合中的所有线程在继续之前执行

时间:2021-12-22 06:59:07

Is there a problem with this type of implementation to wait for a batch of threads to complete before moving on, given the following circumstances?:

考虑到以下情况,这种类型的实现是否存在问题,等待一批线程在继续之前完成?

  • CCR or PFX cannot be used.
  • 不能使用CCR或PFX。

  • Customer.Prices collection and newCustomer are NOT being mutated.
  • Customer.Prices集合和newCustomer不会发生变异。

  • CloneCustomerPrices performs a deep copy on each of the prices in Customer.Prices collection into a new price Collection.
  • CloneCustomerPrices将Customer.Prices集合中的每个价格执行深层复制到新的价格集合中。

public List[Customer] ProcessCustomersPrices(List [Customer] Customers)
{
[Code to check Customers and  deep copy Cust data into newCustomers]
List[Thread] ThreadList = new List[Thread]();
foreach(Customer cust in Customers)
{
ThreadList.Add(new Thread(() => CloneCustomerPrices(cust.Prices, newCustomer)));
}

Action runThreadBatch = () =>
            {
                 ThreadList.ForEach(t => t.Start());
                 ThreadList.All    (t => t.Join([TimeOutNumber]));
            };

runThreadBatch(CopyPriceModelsCallback, null);

[More Processing]
return newCustomers;
}

2 个解决方案

#1


The waiting implementation seems fine, just be sure that CloneCustomerPrices is thread safe.

等待实现似乎很好,只需确保CloneCustomerPrices是线程安全的。

#2


Makes sense to me, so long as the threads finish by the timeout. Not sure what newCustomer is (same as cust?). If that's the case I also don't know how to plan to return just one of them.

只要线程在超时结束时对我有意义。不确定newCustomer是什么(与cust相同)。如果是这种情况我也不知道如何计划只返回其中一个。

#1


The waiting implementation seems fine, just be sure that CloneCustomerPrices is thread safe.

等待实现似乎很好,只需确保CloneCustomerPrices是线程安全的。

#2


Makes sense to me, so long as the threads finish by the timeout. Not sure what newCustomer is (same as cust?). If that's the case I also don't know how to plan to return just one of them.

只要线程在超时结束时对我有意义。不确定newCustomer是什么(与cust相同)。如果是这种情况我也不知道如何计划只返回其中一个。