异步I / O(从异步webrequest读取流)

时间:2010-11-06 18:42:29

标签: c# httpwebrequest

尝试从异步webrequest中读取ToEnd时遇到了一些问题。这是代码:

    public void GetHTTP(string http)
    {
        request = (HttpWebRequest)WebRequest.Create(http);
        RequestState rs = new RequestState(); // Class to hold state. Can ignore...
        Setup(); // contain statements such as request.Accept =...;
        rs.Request = request;
        IAsyncResult r = (IAsyncResult)request.BeginGetResponse(new AsyncCallback ResponseSetup), rs);
        allDone.WaitOne();
        Referer = http; //Can ignore this...
    }

    private void ResponseSetup(IAsyncResult ar)
    {
        RequestState rs = (RequestState)ar.AsyncState;
        WebRequest request = rs.Request;
        WebResponse response = request.EndGetResponse(ar);
        Stream ResponseStream = response.GetResponseStream();
        rs.ResponseStream = ResponseStream;
        IAsyncResult iarRead = ResponseStream.BeginRead(rs.BufferRead, 0, BUFFER_SIZE, new AsyncCallback(ReadCallBack), rs);
        StreamReader reader = new StreamReader(ResponseStream);
        information = reader.ReadToEnd();
        //The problem is right here; ReadToEnd.
    }

当尝试调用readToEnd方法时,我收到以下错误消息:该流不支持并发I / O读取或写入操作。

我已经搜索过了,但我找不到解决这个问题的方法。如何解决?

1 个答案:

答案 0 :(得分:1)

那是因为你正在尝试做两次读取。对BeginRead的调用启动了读操作。然后ReadToEnd在同一个流上启动另一个读操作。

我认为你想要的只是ReadToEnd。移除对ResponseStream.BeginRead的电话。