日期:2014-05-18  浏览次数:21006 次

关闭流的顺序
NetworkStream ns = ...;
StreamReader sr = new StreamReader(ns);
StreamWriter sw = new StreamWrtier(ns);

问题:ns,sr,sw 应如何关闭,用怎样的顺序关闭。sr和sw似乎只能关掉一个。



------解决方案--------------------
StreamReader 和StreamWriter 没什么关系吧。。。NetworkStream 放在最后
------解决方案--------------------
测了一下,发现3者关闭顺序应该如下:
C# code
using System;
using System.IO;
using System.Net.Sockets;
using System.Net;

class Example
{
    static void Main()
    {
        Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        IPAddress hostAddress = Dns.GetHostEntry("localhost").AddressList[0];
        s.Connect(hostAddress, 8000);

        NetworkStream ns = new NetworkStream(s);
        StreamReader sr = new StreamReader(ns);
        char[] buffer=new char[5];
        sr.Read(buffer, 0, 1);
        StreamWriter sw = new StreamWriter(ns);
        sw.Write(true);

        sw.Close();
        sr.Close();
        ns.Close();
    }
}