将TransactionScope与Parallel.Foreach循环一起使用

时间:2017-08-18 10:17:30

标签: c# parallel-processing transactions task-parallel-library parallel.foreach

我正在尝试使用Transaction with Parallel.Foreach

代码段:

List<int> iList = new List<int>(); // Having int random numbers

/// To check final collection count

ConcurrentQueue<int> q= new ConcurrentQueue<in>();

using(var scope = new TransactionScope())
{

    Transaction rootTr = Transaction.Current;

    Parallel.ForEach(iLIst, item =>
    {

        DependentTransaction dt = rootTr.DependentClone(DependentCloneOption.RollbackIfNotComplete);

        if(item == 7)
             throw new ArgumentException("7 occurred"); // This is throwing Exception

        q.Enqueue(item);

        Thread.Sleep(5000);

        dt.Complete();
    });

    ts.Complete();
}

但是我得到了异常,但我在队列(q)中看到了值。

我希望完全回滚所有并行处理项,以便在发生故障时队列(q)为空。

0 个答案:

没有答案