处置方法中可以包含非处置代码吗?

时间:2020-08-13 13:34:40

标签: c# dispose idisposable

我已打开代码分析并告诉我正确实现Dispose()

Modify 'UnitOfWork.Dispose' so that it calls Dispose(true), then calls GC.SuppressFinalize on the current object instance

除了附加的代码行,它实际上已正确实现。请参阅Dispose()中的第一行(回滚事务)。如果我在那条评论,CA错误消失了。如果该行未注释,则会出现错误。我不允许在Dispose()中加入该行吗?

    public void Dispose()
    {
        // If the user never called commit, but we are using a transaction, then roll back.
        // If I comment this line, then the CA error about implementing `Dispose()` correctly goes away.
        if (!_commitOccurred && _useTransaction) { _transaction.Rollback(); }

        Dispose(true);
        GC.SuppressFinalize(this); // Already disposed; no need for the GC to finalize.
    }

    protected virtual void Dispose(bool calledFromDisposeAndNotFromFinalizer)
    {
        if (_disposed) { return; }

        if (calledFromDisposeAndNotFromFinalizer)
        {
            if (_transaction != null) { _transaction.Dispose(); _transaction = null; }
            if (_connection != null) { _connection.Dispose(); _connection = null; }
        }

        _disposed = true;
    }

1 个答案:

答案 0 :(得分:1)

清除代码放入重载的Dispose中:

 protected virtual void Dispose(bool calledFromDisposeAndNotFromFinalizer)
 {
    if (_disposed) { return; }

    if (calledFromDisposeAndNotFromFinalizer)
    {
        if (!_commitOccurred && _useTransaction) { _transaction.Rollback(); }
        if (_transaction != null) { _transaction.Dispose(); _transaction = null; }
        if (_connection != null) { _connection.Dispose(); _connection = null; }
    }

    _disposed = true;
 }

至少,这可以确保冗余呼叫不会重新进入。