在循环中使用StreamWriter时出现c# – “Stream not Writable”错误

我正在尝试用C#编写一个工具来帮助QA解决一些网络问题,并且遇到了问题.该程序应该每秒以
JSON格式向服务器发送一个查询.

目前,它工作一次,但在第二次尝试发送查询时,我得到一个例外,因为

“Stream was not writable.”

这是我的代码:

public partial class Form1 : Form
{
    Timer timer1;
    String query;
    String result;

    HttpWebRequest request;
    StreamWriter writeData;
    StreamReader readData;
    HttpWebResponse response;


    public Form1()
    {
        InitializeComponent();
        timer1 = new Timer();
        timer1.Tick += new EventHandler(timer1_Tick);
        timer1.Interval = 1000;
        File.Delete(AppDomain.CurrentDomain.BaseDirectory + "log.txt");
        logOutput.ReadOnly = true;
        request = (HttpWebRequest)WebRequest.Create("a URL goes here");
        request.ContentType = "application/json";
        request.Method = "POST";
        query = "{some json stuff goes here}";
    }

    private void startButton_Click(object sender, EventArgs e)
    {
        if (!timer1.Enabled)
        {
            timer1.Start();
            startButton.Text = "Stop";
        }
        else
        {
            timer1.Stop();
            startButton.Text = "Start";
        }
    }

    private void timer1_Tick(object sender, EventArgs e)
    {
        writeData = new StreamWriter(request.GetRequestStream());
        writeData.Write(query);
        writeData.Flush();
        writeData.Close();

        response = (HttpWebResponse)request.GetResponse();
        readData = new StreamReader(response.GetResponseStream());

        result = readData.ReadToEnd();
        logOutput.Text = result;
        File.AppendAllText(AppDomain.CurrentDomain.BaseDirectory + "log.txt", result + "\r\n");
    }
}
}

谁知道我做错了什么?

最佳答案 首先,使用全局变量停止.将streamwriter,streamreader,httpwebresponse等移动到实际的tick方法中.

任何实现IDisposable的东西,大多数东西都应该是非常局部的变量,它们不会被闲置并且被包含在使用子句中.

一旦您的方法完成,基本上您的请求对象将被关闭.

像这样的东西会更好:

private void timer1_Tick( object sender, EventArgs e ) {

    HttpWebRequest request = (HttpWebRequest)WebRequest.Create("a URL goes here");

    request.ContentType = "application/json";
    request.Method = "POST";
    String query = "{some json stuff goes here}";
    String result = String.Empty;

    using ( StreamWriter writeData = new StreamWriter(request.GetRequestStream()) ) {
        writeData.Write(query);
        writeData.Flush();

        using ( HttpWebResponse response = (HttpWebResponse)request.GetResponse() ) {
            using ( StreamReader readData = new StreamReader(response.GetResponseStream()) ) {
                result = readData.ReadToEnd();
            }
        }
    }

    logOutput.Text = result;
    File.AppendAllText(AppDomain.CurrentDomain.BaseDirectory + "log.txt", result + "\r\n");
}

}

点赞