我正在寻找一种利用多线程(可能是异步委托(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().
的每次调用都是相同的(很明显)。 因此,我的问题是:
DoTests()
方法之外,还有其他更有效的方法来执行上述操作吗? 最佳答案
希望我完全理解你的意思。
1.是的,如果您在不同的线程上多次调用DoTests
,则代码性能会更好。假设您没有被锁定在GetTestResults
和UpdateXXX
方法中。
2.这基本上取决于您调用的方法(GetTestResults
和UpdateXXX
方法)的实现
3.您打算同时调用几个DoTests
,对吗?那么,为什么要问普通循环呢?
实际上,我没有完全了解您的交易情况。据我了解,您会使用自己的交易,对吗?否则,我相信您在序列化事务更新时会遇到麻烦。
关于c# - 与数据库多线程,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8151961/