Does SslStream.Dispose dispose its inner stream

天大地大妈咪最大 提交于 2021-02-05 12:05:12

问题


I use NetworkStream with sockets in an SslStream socket server as follows:

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

My question is, if when I call sslStream.Dispose(), will the SslStream dispose/close its inner stream and its socket too?

Or do I need to explicitly close all three resources with sslStream.Close(), stream.Close() and socket.Close()?


回答1:


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.



来源:https://stackoverflow.com/questions/9934975/does-sslstream-dispose-dispose-its-inner-stream

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!