iDisposable和iAsyncdisposable如何一起工作?

发布于 2025-01-23 22:27:18 字数 3112 浏览 2 评论 0原文

下面的类不是密封,这意味着它被认为是可继承的。 I took IDisposable/IAsyncDisposable implementation from here而且我试图理解为什么.dispose在Dispose和DispoSeasync中都重复了调用。有人可以向我解释它的工作原理/还是我会说低水平,所以我实际上知道将来如何使用它?

public class Client : IDisposable, IAsyncDisposable
{
    private readonly ILogger<Client> _logger;
    private readonly Channel<string> _outputChannel;
    private ClientWebSocket? _clientWebSocket;
    private CancellationTokenSource? _cancellationSource;
    private Task _receiving = Task.CompletedTask;
    private Task _sending = Task.CompletedTask;

    public Client(ILoggerFactory? loggerFactory = default)
    {
        _logger = (loggerFactory ?? NullLoggerFactory.Instance).CreateLogger<Client>();
    }

    public bool IsDisposed { get; protected set; }

    ...

    /// <summary>
    ///     Checks if this object has been disposed.
    /// </summary>
    /// <exception cref="ObjectDisposedException">Thrown if the object has been disposed.</exception>
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    protected void DoDisposeChecks()
    {
        if (IsDisposed)
        {
            throw new ObjectDisposedException(nameof(Client));
        }
    }

    /// <summary>
    ///     Disposes of managed and unmanaged resources.
    /// </summary>
    /// <param name="disposeManaged">A value indicating whether or not to dispose of managed resources.</param>
    protected virtual void Dispose(bool disposeManaged)
    {
        if (IsDisposed)
        {
            return;
        }

        if (disposeManaged)
        {
            _logger.LogDebug("Socket {Id} is disposing", Id);

            _clientWebSocket?.Dispose();
            _cancellationSource?.Dispose();

            _outputChannel.Writer.TryComplete();

            _logger.LogDebug("Socket {Id} disposed", Id);
        }

        IsDisposed = true;
    }

    /// <summary>
    ///     Asynchronously disposes of managed resources.
    /// </summary>
    /// <returns>A task representing the asynchronous operation.</returns>
    protected virtual ValueTask DisposeAsyncCore()
    {
        if (IsDisposed)
        {
            return default;
        }

        _logger.LogDebug("Socket {Id} is disposing", Id);

        _clientWebSocket?.Dispose();
        _cancellationSource?.Dispose();

        _outputChannel.Writer.TryComplete();

        _logger.LogDebug("Socket {Id} disposed", Id);

        IsDisposed = true;

        return default;
    }

    /// <inheritdoc />
    public async ValueTask DisposeAsync()
    {
        await DisposeAsyncCore().ConfigureAwait(false);
        Dispose(false);
        GC.SuppressFinalize(this);
    }

    /// <inheritdoc />
    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }
}

The class below is not sealed, which means it is considered inheritable. I took IDisposable/IAsyncDisposable implementation from here and I'm trying to understand why the .Dispose calls are duplicated in both Dispose and DisposeAsync. Will someone be able to explain to me how it works more deeply/or I would say low level, so I actually know how to use it in future?

public class Client : IDisposable, IAsyncDisposable
{
    private readonly ILogger<Client> _logger;
    private readonly Channel<string> _outputChannel;
    private ClientWebSocket? _clientWebSocket;
    private CancellationTokenSource? _cancellationSource;
    private Task _receiving = Task.CompletedTask;
    private Task _sending = Task.CompletedTask;

    public Client(ILoggerFactory? loggerFactory = default)
    {
        _logger = (loggerFactory ?? NullLoggerFactory.Instance).CreateLogger<Client>();
    }

    public bool IsDisposed { get; protected set; }

    ...

    /// <summary>
    ///     Checks if this object has been disposed.
    /// </summary>
    /// <exception cref="ObjectDisposedException">Thrown if the object has been disposed.</exception>
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    protected void DoDisposeChecks()
    {
        if (IsDisposed)
        {
            throw new ObjectDisposedException(nameof(Client));
        }
    }

    /// <summary>
    ///     Disposes of managed and unmanaged resources.
    /// </summary>
    /// <param name="disposeManaged">A value indicating whether or not to dispose of managed resources.</param>
    protected virtual void Dispose(bool disposeManaged)
    {
        if (IsDisposed)
        {
            return;
        }

        if (disposeManaged)
        {
            _logger.LogDebug("Socket {Id} is disposing", Id);

            _clientWebSocket?.Dispose();
            _cancellationSource?.Dispose();

            _outputChannel.Writer.TryComplete();

            _logger.LogDebug("Socket {Id} disposed", Id);
        }

        IsDisposed = true;
    }

    /// <summary>
    ///     Asynchronously disposes of managed resources.
    /// </summary>
    /// <returns>A task representing the asynchronous operation.</returns>
    protected virtual ValueTask DisposeAsyncCore()
    {
        if (IsDisposed)
        {
            return default;
        }

        _logger.LogDebug("Socket {Id} is disposing", Id);

        _clientWebSocket?.Dispose();
        _cancellationSource?.Dispose();

        _outputChannel.Writer.TryComplete();

        _logger.LogDebug("Socket {Id} disposed", Id);

        IsDisposed = true;

        return default;
    }

    /// <inheritdoc />
    public async ValueTask DisposeAsync()
    {
        await DisposeAsyncCore().ConfigureAwait(false);
        Dispose(false);
        GC.SuppressFinalize(this);
    }

    /// <inheritdoc />
    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文