我正在寻找一种利用多线程(可能是异步委托(delegate))进行同步操作的策略。我是多线程的新手,所以我将首先概述我的场景。现在这个同步操作是根据提供的参数对一组数据(投资组合)完成的。 (伪代码)实现如下:
public DataSet DoTests(int fundId, DateTime portfolioDate)
{
// Get test results for the portfolio
// Call the database adapter method, which in turn is a stored procedure,
// which in turns runs a series of "rule" stored procs and fills a local temp table and returns it back.
DataSet resultsDataSet = GetTestResults(fundId, portfolioDate);
try
{
// Do some local processing on the results
DoSomeProcessing(resultsDataSet);
// Save the results in Test, TestResults and TestAllocations tables in a transaction.
// Sets a global transaction which is provided to all the adapter methods called below
// It is defined in the Base class
StartTransaction("TestTransaction");
// Save Test and get a testId
int testId = UpdateTest(resultsDataSet); // Adapter method, uses the same transaction
// Update testId in the other tables in the dataset
UpdateTestId(resultsDataSet, testId);
// Update TestResults
UpdateTestResults(resultsDataSet); // Adapter method, uses the same transaction
// Update TestAllocations
UpdateTestAllocations(resultsDataSet); // Adapter method, uses the same transaction
// It is defined in the base class
CommitTransaction("TestTransaction");
}
catch
{
RollbackTransaction("TestTransaction");
}
return resultsDataSet;
}
现在的要求是对多组数据进行处理。一种方法是在循环中调用上述 DoTests()
方法并获取数据。我宁愿并行进行。但是有一些问题:
StartTransaction()
方法每次被调用时都会创建一个连接(和事务)。- 所有底层数据库表、过程对于
DoTests() 的每次调用都是相同的。
(显然)。
因此我的问题是:
- 无论如何使用多线程都会提高性能吗?
- 发生死锁的可能性有多大,尤其是在创建新的 TestId 并保存测试、TestResults 和 TestAllocations 时?如何处理这些僵局?
- 除了重复遍历
DoTests()
方法之外,还有其他更有效的方法来执行上述操作吗?
最佳答案
希望我完全理解你的意思。
1. 是的,如果您在不同的线程上多次调用 DoTests
,您的代码性能会更好。假设您没有被锁定在 GetTestResults
和 UpdateXXX
方法中。
2. 这基本上取决于您调用的方法的实现(GetTestResults
和 UpdateXXX
方法)
3. 您打算同时调用多个 DoTests
,对吗?那你为什么要问普通循环?
实际上我没有完全了解交易。据我了解,每个实例都会使用自己的事务,对吗?否则,我相信您会在序列化事务更新时遇到麻烦。
关于c# - 多线程与数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8151961/