不要在TransactionScope中使用"using"语句

3
我总是使用以下格式来使用TransactionScope。
using(TransactionScope scope = new TransactionScope()){
  ....
}
有时我想将TransactionScope包装到一个新类中,例如DbContext类,我想使用如下语句:
dbContext.Begin();
...
dbContext.Submit();
似乎TransactionScope类需要使用"using"语句进行处理,我想知道是否有任何不使用"using"的方法。
3个回答

17
using (var scope = new TransactionScope())
{
    …
}

函数等效于:

var scope = new TransactionScope();
try
{
    …
}
finally
{
    scope?.Dispose();
}
(也就是说,你只能在实现了IDisposable接口的类型上使用using语句。)

10

您可以按照以下方式设计您的 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();
}

2

你可以使用 try..finally 并手动调用 Dispose 方法,但这不如使用 using 语句清晰明了。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接