加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 不要对TransactionScope使用“using”语句

发布时间:2020-12-15 20:52:25 所属栏目:百科 来源:网络整理
导读:我总是使用以下格式来使用transactionscope. using(TransactionScope scope = new TransactionScope()){ ....} 有时我想将Transactionscope包装到一个新类,例如DbContext类,我想使用像这样的语句 dbContext.Begin();...dbContext.Submit(); 似乎事务管理器类
我总是使用以下格式来使用transactionscope.

using(TransactionScope scope = new TransactionScope()){
  ....
}

有时我想将Transactionscope包装到一个新类,例如DbContext类,我想使用像这样的语句

dbContext.Begin();
...
dbContext.Submit();

似乎事务管理器类需要使用“using”语句来进行处理,我想知道是否还有使用“使用”.

解决方法

您可以按如下方式设计DbContext类:

public sealed class DbContext : IDisposable
{
    private bool disposed;
    private TransactionScope scope;

    public void Begin()
    {
        if (this.disposed) throw new ObjectDisposedException();
        this.scope = new TransactionScope();
    }

    void Submit()
    {
        if (this.disposed) throw new ObjectDisposedException();
        if (this.scope == null) throw new InvalidOperationException();
        this.scope.Complete();
    }

    public void Dispose()
    {
        if (this.scope != null)
        {
            this.scope.Dispose();
            this.scope = null;
        }
        this.disposed = true;
    }
}

你可以按如下方式使用它:

using (var context = new DbContext())
{
    context.Begin();

    // Operations.

    context.Submit();
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读