2010-11-06 94 views
0

嘗試從異步webrequest進行readToEnd時遇到了一些問題。下面的代碼:異步I/O(從異步webrequest讀取流)

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讀取或寫入操作。

我查過了,但找不到解決這個問題的辦法。它如何被修復?

+0

'ReadToEnd'是一種阻塞方法,您可以調用*代替使用異步方法。在異步'ReadCallBack'中,你將不得不使用提供給緩衝區的數據自己讀取數據。 – 2010-11-06 18:49:56

回答

1

這是因爲你試圖做兩個讀取。對BeginRead的調用啓動讀取操作。然後ReadToEnd在同一個流上啓動另一個讀取操作。

我想你想要的只是ReadToEnd。取消對ResponseStream.BeginRead的呼叫。

+0

我是這樣一個白癡大聲笑...謝謝。這是一個非常簡單的問題。 – user385048 2010-11-06 19:07:39