gpt4 book ai didi

c# - 处理 CryptoStream 还是处理底层 Stream?

转载 作者:太空宇宙 更新时间:2023-11-03 12:25:05 24 4
gpt4 key购买 nike

我有一个 CryptoStream 和一个底层 Stream。我不能使用 using block 来处理 CryptoStream,因为这也会处理我需要保持打开状态的底层 Stream。解决方案似乎只是忽略 CryptoStream 并在需要时处理 Stream 。但也许保留对 CryptoStream 的引用并处理它以防止某些资源泄漏很重要?

此外,即使我不处置 CryptoStream,如果它超出范围,GC 也可能处置它,然后还处置底层的 Stream,(会不会太早了,因为我还需要 Stream)?

最佳答案

来自 CryptoStream.cs (ln 695) :

    protected override void Dispose(bool disposing) {
try {
if (disposing) {
if (!_finalBlockTransformed) {
FlushFinalBlock();
}
_stream.Close();
}
}
finally {
try {
// Ensure we don't try to transform the final block again if we get disposed twice
// since it's null after this
_finalBlockTransformed = true;
// we need to clear all the internal buffers
if (_InputBuffer != null)
Array.Clear(_InputBuffer, 0, _InputBuffer.Length);
if (_OutputBuffer != null)
Array.Clear(_OutputBuffer, 0, _OutputBuffer.Length);

_InputBuffer = null;
_OutputBuffer = null;
_canRead = false;
_canWrite = false;
}
finally {
base.Dispose(disposing);
}
}
}

如您所见,如果您不想释放 CryptoStream,您应该调用公共(public)的 FlushFinalBlock 方法。此方法会清除输入和输出缓冲区,因此不会在使用的 CryptoStream 中存储任何敏感信息。

GC 是否会关闭底层的 Stream?没有。为此,必须使用 true 作为参数值调用 Dispose 方法,但这仅在 Stream.Close 方法(称为来自 Stream.Dispose)。即使 CryptoStream 将实现终结器,在执行 Finalize 时调用引用对象的 Dispose 也不是一个好习惯。终结器应该只用于释放非托管资源。

关于c# - 处理 CryptoStream 还是处理底层 Stream?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45401733/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com