2

我正在爲Windows Phone 7編程一個應用程序。此應用程序首先發送,然後通過HttpWebRequest從服務器接收數據。大多數時候它工作正常,但有時,在正確接收到一部分數據之後,我在Stream.Read()函數中得到一個NullReferenceException。NullReferenceException從異步HttpWebRequest流讀取

當用戶按下按鈕時,通信開始。然後,我創建的HttpWebRequest:

HttpWebRequest request = (HttpWebRequest) WebRequest.Create(sUri); 
request.Method = "POST"; 
request.BeginGetRequestStream(GetRequestStreamCallback, request); 

請求回調方法:

private void GetRequestStreamCallback(IAsyncResult asynchronousResult) 
{      
    HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState; 
    postStream = request.EndGetRequestStream(asynchronousResult); 

    this.bSyncOK = Send(); //This is my method to send data to the server 
    postStream.Close(); 

    if (this.bSyncOK) 
    request.BeginGetResponse(GetResponseCallback, request); 
    else 
    manualEventWait.Set(); //This ManualResetEvent notify a thread the end of the communication, then a progressbar must be hidden 
} 

響應回調方法:

private void GetResponseCallback(IAsyncResult asynchronousResult) 
{ 
    HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState; 
    using (HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult)) 
    { 
    using (streamResponse = new StreamReader(response.GetResponseStream())) 
    { 
     this.bSyncOK = Recv(); //This is my generic method to receive the data 
     streamResponse.Close(); 
    } 
    response.Close(); 
    } 
    manualEventWait.Set(); //This ManualResetEvent notify a thread the end of the communication, then a progressbar must be hidden 
} 

最後,這是我得到的異常讀數代碼流數據:

int iBytesLeidos; 
byte[] byteArrayUTF8 = new byte[8]; 

iBytesLeidos = streamResponse.BaseStream.Read(byteArrayUTF8, 0, 8); //NullReferenceException!!! -Server always send 8 bytes here- 

當應用程序啓動時,我創建了一個經常將信息發送到服務器的後臺線程。背景和手動通信可以同時運行。這可能是一個問題嗎?

謝謝。

回答

1

如果streamResponse是全局變量,它可能會導致從另一個線程訪問的情況下的問題。通過你的StreamRecv作爲第二個片段參數

using (StreamReader streamResponse = new StreamReader(response.GetResponseStream())) 
{ 
    this.bSyncOK = Recv(streamResponse); //This is my generic method to receive the data 
    streamResponse.Close(); 
} 
+0

它的工作原理。非常感謝你 – 2012-01-16 10:49:55

0

您的streamResponse在後面的代碼段中聲明在哪裏?它與3d片段中的對象相同嗎?也許你只是使用另一個變量,而不是實際的流。

+0

是的,所有的代碼都屬於同一個類。這是「streamResponse」的聲明 - >「private static StreamReader streamResponse;」 – 2011-12-29 13:18:08

+0

你可以檢查'streamResponse'或'.BaseStream'是否爲空? – 2011-12-29 13:43:52

+0

streamResponse似乎是正確的,.BaseStream不可訪問 – 2011-12-29 19:19:06

0

,試圖刪除 「postStream.Close();」。