foreach (int tranQuote in transactionIds)
{
CompassIntegration compass = new CompassIntegration();
Chatham.Business.Objects.Transaction tran = compass.GetTransaction(tranQuote);
// then we want to send each trade through the PandaIntegration
// class with either buildSchedule, fillRates, calcPayments or
// a subset of the three
PandaIntegrationOperationsWrapper wrapper = new PandaIntegrationOperationsWrapper { buildSchedule = false, calcPayments = true, fillRates = true };
new PandaIntegration().RecalculateSchedule(tran, wrapper);
// then we call to save the transaction through the BO
compass.SaveTransaction(tran);
}
这里有两行需要很长时间。 transactionIds
中有大约 18k 条记录,我这样做是为了。
GetTransaction
和SaveTransaction
是最耗时的两行代码,但老实说,我只是想将循环中发生的事情线程化以提高性能。
在不遇到任何 CPU 问题或类似问题的情况下将其线程化的最佳方法是什么?我不太确定有多少线程是安全的或如何进行线程管理或诸如此类的事情。
谢谢你们。
最佳答案
TPL 将提供必要的节流和管理。
//foreach (int tranQuote in transactionIds) { ... }
Parallel.ForEach(transactionIds, tranQuote => { ... } );
它确实需要 Fx4 或更高版本,并且循环内的所有代码都必须是线程安全的。
目前尚不清楚您的 GetTransaction 和 SaveTransaction 是否可以安全地同时调用。
关于c# - 在循环内部线程化以提高性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8929108/