我正在爲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-
當應用程序啓動時,我創建了一個經常將信息發送到服務器的後臺線程。背景和手動通信可以同時運行。這可能是一個問題嗎?
謝謝。
它的工作原理。非常感謝你 – 2012-01-16 10:49:55