c# - 在循环内部线程化以提​​高性能

标签 c# .net multithreading loops thread-safety

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 条记录,我这样做是为了。

GetTransactionSaveTransaction 是最耗时的两行代码,但老实说,我只是想将循环中发生的事情线程化以提​​高性能。

在不遇到任何 CPU 问题或类似问题的情况下将其线程化的最佳方法是什么?我不太确定有多少线程是安全的或如何进行线程管理或诸如此类的事情。

谢谢你们。

最佳答案

TPL 将提供必要的节流和管理。

//foreach (int tranQuote in transactionIds) { ... }
Parallel.ForEach(transactionIds, tranQuote => { ... } );

它确实需要 Fx4 或更高版本,并且循环内的所有代码都必须是线程安全的。
目前尚不清楚您的 GetTransaction 和 SaveTransaction 是否可以安全地同时调用。

关于c# - 在循环内部线程化以提​​高性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8929108/

相关文章:

c# - .net 加密数据库表

在 Windows 上创建线程数组

c++ - C++ 线程中的意外输出

c# - 如何使用 sql 查询在 SQL Server 中存储来自 C# 的哈希值

c# - C# 和 VB.NET 中的即时窗口行为差异

c# - 基于亮度的位图像素替换

c# - 在 C# 中返回匿名类型

c# - 我如何验证这种情况下的 web api 请求对象?

java - JMS session 线程影响

c# - 项目引用条件包含多个条件