我正在创建一种机制,可以将大量新记录批量插入(导入)到ORACLE数据库中。我正在使用多个线程和依赖事务:
创建线程:
const int ThreadCount = 4;
using (TransactionScope transaction = new TransactionScope())
{
List<Thread> threads = new List<Thread>(threadCount);
for (int i = 0; i < ThreadCount; i++)
{
Thread thread = new Thread(WorkerThread);
thread.Start(Transaction.Current.DependentClone(DependentCloneOption.BlockCommitUntilComplete));
threads.Add(thread);
}
threads.ForEach(thread => thread.Join());
transaction.Complete();
}
执行实际工作的方法:
private void WorkerThread(object transaction)
{
using (DependentTransaction dTx = (DependentTransaction)transaction)
using (TransactionScope ts = new TransactionScope(dTx))
{
// The actual work, the inserts on the database, are executed here.
}
}
在此操作期间,我收到System.Data.OracleClient.OracleException
类型的例外,其中包含ORA-24757: duplicate transaction identifier
消息。
我做错了什么?我是以错误的方式实现依赖事务吗?它与Oracle不兼容吗?如果是这样,是否有工作场所?
答案 0 :(得分:1)
我不知道为什么你得到这个例外,但解决方法可能是:
const int ThreadCount = 4;
using (var connection = new OracleConnection(MyConnectionstring))
{
connection.Open();
using (var transaction = connection.BeginTransaction())
{
List<Thread> threads = new List<Thread>(ThreadCount);
for (int i = 0; i < ThreadCount; i++)
{
Thread thread = new Thread(WorkerThread);
thread.Start(transaction);
threads.Add(thread);
}
threads.ForEach(thread => thread.Join());
transaction.Commit();
}
}
和工人阶级看起来像:
private void WorkerThread(object transaction)
{
OracleTransaction trans = (OracleTransaction) transaction;
using (OracleCommand command = trans.Connection.CreateCommand())
{
command.CommandText = "INSERT INTO mytable (x) values (1) ";
command.ExecuteNonQuery();
}
}