SslStream.Dispose是否处理其内部流 [英] Does SslStream.Dispose dispose its inner stream

查看:60
本文介绍了SslStream.Dispose是否处理其内部流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将 NetworkStream SslStream 套接字服务器中的套接字一起使用,如下所示:

  stream = new NetworkStream(socket,true);sslStream =新的SslStream(stream,false); 

我的问题是,如果我调用 sslStream.Dispose()时, SslStream 是否也会处理/关闭其内部流及其套接字?

还是我需要使用 sslStream.Close() stream.Close() socket.Close()显式关闭所有三个资源代码>?

解决方案

如果可能,应该在使用后使用C#的 using 构造来自动"处置流:

 使用(var sslStream = new SslStream(stream,false)){//在这里从流中读取...} 

但是,如果要保留SslStream供以后使用,则必须手动处理.

处理流通常也会关闭该流, Close()方法似乎主要是出于完整性考虑.您可以下载.NET源代码(或使用反编译器),并检查 SslStream.cs 及其基类 AuthenticatedStream.cs 以查看确切的行为.

要回答其余问题- SslStream 在Microsoft的 MSDN 网站上有详细记录,该网站显示 解决方案

If possible, you should use C#'s using construct to dispose the stream 'automatically' after use:

using (var sslStream = new SslStream(stream, false))
{
    // read from stream here...
}

However, if you want to keep the SslStream for later use, you will have to dispose manually.

Disposing a stream typically closes the stream as well, the Close() method seems to be there mostly for completeness. You can download the .NET source code (or use a decompiler), and examine the SslStream.cs and its base class AuthenticatedStream.cs to see the exact behaviour.

To answer the rest of your question - The SslStream is well documented on Microsoft's MSDN site which shows one of SslStream's constructors takes two parameters (also shown by your example). The first parameter is the inner stream - which in your example the NetworkStream object. The second is a boolean called leaveInnerStreamOpen. In your example, you pass false.

It is this second value that determines the behaviour you are asking about: If you pass true, the inner stream will remain open when you close/dipose the SslStream (the stream will also be flushed). If you pass false, then the inner stream will be closed too.

Similarly for the NetworkStream, its constructor also takes a boolean ownsSocket. If this is set to true (as in your example), then disposing/closing the NetworkStream will also close its socket, otherwise it stays open.

Therefore, as your example code stands, you must call both sslStream.Dispose() and stream.Dispose() (the socket is closed automatically).

However, if you change the second parameter in the SslStream's constructor to true in your example code, you can just call sslStream.Dispose() to close the SslStream, the NetworkStream, and its socket.

这篇关于SslStream.Dispose是否处理其内部流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆