1

I need to insert some lines in database and if lines contain errors - all changes need to rollback. I was thinking to use Parallel class. Here is my code

class Program
{
static void Main(string[] args)
{
    List<string> results = new List<string>();
    string[] lines = File.ReadAllLines("d:\\opers2.txt");

    using (TransactionScope trans = new TransactionScope())
    {
        System.Threading.Tasks.Parallel.For(0, lines.Count(), i =>
            {
                string[] parts = lines[i].Split('\t');
                string answer = LoadOper(parts[9], parts[7], parts[0]);

                if (!string.IsNullOrEmpty(answer))
                    results.Add(answer);
            });

        //trans.Complete();
    }
}

static string LoadOper(string typeName, string summ, string operDate)
{
    System.Transactions.Transaction trans = System.Transactions.Transaction.Current;
    string answer = trans == null ? "NULL" : "TRANSACTION";
    using (OperEntities context = new OperEntities())
    {
        try
        {
            DateTime dt = DateTime.Parse(operDate);
            decimal summa = Decimal.Parse(summ);
            OperationType type = context.OperationTypes.FirstOrDefault(t => t.name == typeName);

            Operation oper = new Operation()
            {
                dt_oper = dt,
                summ = summa,
                OperationType = type
            };

            context.Operations.AddObject(oper);
            context.SaveChanges();
        }
        catch (Exception ex)
        {
            return answer + " " + ex.Message;
        }
    }
    return answer;
}
}

But some threads has Transaction.Current = null in LoadOper function.

Why?

user2049622
  • 71
  • 1
  • 8
  • See the answers to [this SO question](http://stackoverflow.com/questions/673530/transactionscope-and-multi-threading) and the [example on MSDN](http://msdn.microsoft.com/en-us/library/system.transactions.dependenttransaction.aspx). – Richard Deeming Feb 13 '13 at 13:15
  • did you get solution ? – Kiquenet May 21 '19 at 20:27

0 Answers0