开发者

Passing TransactionScope to tasks created by Parallel.Invoke

开发者 https://www.devze.com 2023-04-02 02:37 出处:网络
I want the TxJobs, which are running in parallel, to create a scope from this parent transaction. How do I make this work?

I want the TxJobs, which are running in parallel, to create a scope from this parent transaction. How do I make this work?

using (var tx = TransactionScope()) {
    Parallel.Invoke(TxJob1, TxJob2) ;
    tx.Complete();
}

I passed in a DependentClone:

using (var tx = new TransactionScope()) {
    var dtx1 = Transaction.Current.DependentClone(
        DependentCloneOption.RollbackIfNotComplete) ;
    var dtx2 = Transaction.Current.DependentClone(
        DependentCloneOption.RollbackIfNotComplete) ;
    Parallel.Invoke(() => TxJob1(dtx1), () => TxJob2(dtx2)) ;
    tx.Complete();
}

In the TxJob1 and TxJob2 methods, it works if I just call Complete on the DependentClones. However, if I create a scope from the clone I get a TransactionAbortedException:

void TxJob1(Transaction dt) {
    using (var tx = new TransactionScope(dt)) {
        Console.WriteLine(dtx.TransactionInformation.LocalIdentifier);
        tx.Complete();
    }
}

The exception is raised by the call to Complete in the main method, not in TxJobs. Why does this fail?

[edit] If I explicitly cal开发者_Python百科l Complete on the DependentTransaction in TxJobs, then it works. If I don't call Complete on the new TransactionScope in TxJobs (triggering a rollback), then the parent transaction fails. It looks like I have to call Complete on both Transaction objects.


It looks like I have to call Complete on both the dependent clone and the TransactionScope. MS does the same in their sample code.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号