2015.10.14-TransactionScope测试

本文探讨了一个在代码中使用事务范围执行和回滚的案例,重点关注同步和异步SQL操作的回滚效果,揭示了内存对象未随事务回滚的现象。

测试代码:

int i = 10;
int xx = 20;
List<string> lst = null;

Action doSth = () =>
{
    using (var db = new TestSystemEntities())
    {
        var f = db.ABC.ToList();
        f.ForEach(x => x.C = "TestTransactionScope");
        db.SaveChanges();
    }

    new Task(() =>
    {
        using (var db = new TestSystemEntities())
        {
            var f = db.ABC.ToList();
            f.ForEach(x => x.C = "AsyncTestTransactionScope");
            db.SaveChanges();
        }
    }).Start();

    i = 20;
    lst.Insert(0, "xx");
    xx = 100;
};

try
{
    TransactionOptions tr = new TransactionOptions()
    {
        IsolationLevel = IsolationLevel.Serializable,
        Timeout = TransactionManager.MaximumTimeout
    };
    using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, tr))
    {
        doSth();
        scope.Complete();
    }
}
catch (Exception ex)
{
    Console.WriteLine("exception happens");
}

Console.WriteLine("i: {0}, xx: {1}", i, xx);

上面的代码,由于lst一直为null,当执行到lst.Insert的时候,会出现异常,触发事务回滚。

测试结论:回滚效果,同步SQL里面的操作回滚了,但内存中object并未回滚,异步的SQL里面也未回滚.

如图:

转载于:https://www.cnblogs.com/icyJ/p/TransactionScope.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值