1

我需要在数据库中插入一些行,如果行包含错误 - 所有更改都需要回滚。我正在考虑使用 Parallel 类。这是我的代码

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

但是有些线程在 LoadOper 函数中有 Transaction.Current = null 。

为什么?

4

0 回答 0