我可以在处置方法中使用非处置代码吗?

Can I have non-disposing code in a dispose method?

我打开了代码分析并告诉我正确实施 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;
    }

清理代码进入重载 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;
 }

至少这保证了冗余调用不会re-enter。