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

c# – 不要对TransactionScope使用“using”语句,第1张

概述我总是使用以下格式来使用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();}
总结

以上是内存溢出为你收集整理的c# – 不要对TransactionScope使用“using”语句全部内容,希望文章能够帮你解决c# – 不要对TransactionScope使用“using”语句所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://www.54852.com/langs/1226386.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-05
下一篇2022-06-05

发表评论

登录后才能评论

评论列表(0条)

    保存