处理包含流的派生流
Disposing derived stream containing streams
我有以下 class 来自流:
public class EncryptedStream : Stream
{
private readonly SymmetricAlgorithm _engine;
private readonly CryptoStream _cryptoStream;
private readonly Stream _inputStream;
//Standard overrides of stream
}
我正在寻找一种方法来处理此 class 中的基本流以及所有流和资源。我已经阅读了一些有关处置模式的内容,并且由于流已经实现了 IDisposable,所以我的想法是在此 class 中进行处置,我将执行以下操作:
protected override void Dispose(bool disposing)
{
if (disposing)
{
_engine.Dispose();
_cryptoStream.Dispose();
_inputStream.Dispose();
}
}
这应该在处理基本流时被调用,因为基本流 IDisposable 调用 Close() 调用 Dispose(true)。
这似乎行得通,这种方法有什么缺点吗?而且,我需要在 If 语句之后调用 base.Dispose(disposing) 吗?我不这么认为,因为这基本上已经通过首先在基本流上调用 Dispose 来完成,对吗?
有没有其他不那么复杂的方法来处理这个问题,因为这花了我一段时间才理解。
你有的就是好的。不需要调用Stream::Dispose(bool)
,它是一个空体的虚方法。
我也建议你保留这个 link handy, it lists a lot of Dos and Don'ts for the Dispose Pattern。
(复制自 Stream.cs)
/// <summary>Releases the unmanaged resources used by the <see cref="T:System.IO.Stream" /> and optionally releases the managed resources.</summary>
/// <param name="disposing">
/// <see langword="true" /> to release both managed and unmanaged resources; <see langword="false" /> to release only unmanaged resources.</param>
[__DynamicallyInvokable]
protected virtual void Dispose(bool disposing)
{
}
我有以下 class 来自流:
public class EncryptedStream : Stream
{
private readonly SymmetricAlgorithm _engine;
private readonly CryptoStream _cryptoStream;
private readonly Stream _inputStream;
//Standard overrides of stream
}
我正在寻找一种方法来处理此 class 中的基本流以及所有流和资源。我已经阅读了一些有关处置模式的内容,并且由于流已经实现了 IDisposable,所以我的想法是在此 class 中进行处置,我将执行以下操作:
protected override void Dispose(bool disposing)
{
if (disposing)
{
_engine.Dispose();
_cryptoStream.Dispose();
_inputStream.Dispose();
}
}
这应该在处理基本流时被调用,因为基本流 IDisposable 调用 Close() 调用 Dispose(true)。
这似乎行得通,这种方法有什么缺点吗?而且,我需要在 If 语句之后调用 base.Dispose(disposing) 吗?我不这么认为,因为这基本上已经通过首先在基本流上调用 Dispose 来完成,对吗?
有没有其他不那么复杂的方法来处理这个问题,因为这花了我一段时间才理解。
你有的就是好的。不需要调用Stream::Dispose(bool)
,它是一个空体的虚方法。
我也建议你保留这个 link handy, it lists a lot of Dos and Don'ts for the Dispose Pattern。
(复制自 Stream.cs)
/// <summary>Releases the unmanaged resources used by the <see cref="T:System.IO.Stream" /> and optionally releases the managed resources.</summary>
/// <param name="disposing">
/// <see langword="true" /> to release both managed and unmanaged resources; <see langword="false" /> to release only unmanaged resources.</param>
[__DynamicallyInvokable]
protected virtual void Dispose(bool disposing)
{
}