获取异常“重复事务标识符”;而使用Transaction.Current.DependentClone

本文关键字:Transaction DependentClone Current 异常 标识符 事务 获取 | 更新日期: 2023-09-27 18:18:29

我正在创建一种机制来批量插入(导入)大量新记录到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不兼容吗?如果是这样,有没有解决办法?

获取异常“重复事务标识符”;而使用Transaction.Current.DependentClone

我不知道为什么你得到这个异常,但一个工作可能是:

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();
    }
}