2011-07-12 44 views
2

我使用我的代碼調用HttpWebRequest.BeginGetResponse()方法從我的服務器獲取數據。服務器生成的內容範圍可能從幾KB到幾GB不等。HttpWebRequest.BeginGetResponse完成太遲

我的問題是,HttpWebRequest.BeginGetResponse完成得太晚了。在建立與服務器的連接並收到HTTP頭後,它應該立即完成。

這裏使用GET方法的示例代碼:

public bool StartDownload() 
{ 
    try 
    { 
     HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(m_getUrl); 
     myHttpWebRequest.Method = "GET"; 

     // Start the asynchronous request. 
     m_requestState = new RequestState(); 
     m_requestState.request = myHttpWebRequest; 

     myHttpWebRequest.BeginGetResponse(new AsyncCallback(ResponseCompleted), m_requestState); 
    } 
    catch (Exception) 
    { 
     m_requestState = null; 
    } 

    return m_requestState != null; 
} 

private void ResponseCompleted(IAsyncResult result) 
{ 
    RequestState myRequestState = (RequestState)result.AsyncState; 
    HttpWebRequest myHttpWebRequest = myRequestState.request; 

    m_logger.LogMessage("ResponseCompleted notification received!"); 

    HttpWebResponse response = null; 
    try 
    { 
     response = (HttpWebResponse)myHttpWebRequest.EndGetResponse(result); 
    } 
    catch (Exception) 
    { 
    } 
    ....... 
} 

我運行使用的「代碼http://www.kernel.org/pub/linux/kernel/v2.6/linux-2.6.39.1 .tar.bz2「爲例,結果如下所示:

hh:mm:ss.ms 
12:51:30.9440000 - Download started! 
12:53:04.8520000 - ResponseCompleted notification received! 
12:53:04.8560000 - Header received! 
12:53:04.8570000 - DataReceived: 524288 bytes 
......................................... 
12:53:04.8940000 - DataReceived: 78818 bytes 
12:53:04.8940000 - Request data received! 
12:53:04.8940000 - Received bytes: 76100578 

可以在日誌中輕鬆檢測到問題。無法花費更多的時間連接,38毫秒下載大約72.5 MB。 看起來數據是在手機的某個地方下載的,並且只有在本地可用完整內容時,纔會將RequestComplete通知發送給應用程序。這對我來說並不合適,因爲我需要顯示操作進度。

我在WP7(也在WP7.1上)的設備和仿真器上得到了相同的結果。

我在Windows桌面上運行相同的代碼,它運行正常:請求在一秒內完成,其餘下載需要大約1-2分鐘。

在WP7或WP 7.1上有解決方案嗎? 新引入的WP 7.1 API「後臺文件傳輸」沒有幫助,因爲我需要完全控制HTTP標頭和內容。並非我對服務器所做的所有HTTP請求都會生成文件作爲輸出。

謝謝!
Mihai

回答

3

如果您想要關閉數據流,則需要禁用響應緩衝。您可以將AllowReadStreamBuffering設置爲false

HttpWebRequest myHttpWebRequest = WebRequest.CreateHttp(m_getUrl); 
myHttpWebRequest.Method = "GET"; 
myHttpWebRequest.AllowReadStreamBuffering = false; 
+0

謝謝理查德! – Mihai

+0

我還有一個問題。這與流讀取取消有關。我發佈在'http://stackoverflow.com/questions/6679480/how-to-cancel-reading-from-a-stream-obtained-using-httpwebresponse-getresponsestr'謝謝! – Mihai