Windows Phone 7用のアプリケーションをプログラミングしています。このアプリケーションは、最初にHttpWebRequestを介してサーバーからデータを送信し、次に受信します。ほとんどの場合は正常に機能しますが、データの一部を適切に受信した後、Stream.Read()関数でNullReferenceExceptionが発生する場合があります。
ユーザーがボタンを押すと通信が始まります。次に、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-
アプリケーションが起動すると、サーバーに情報を頻繁に送信するバックグラウンドスレッドを作成します。バックグラウンド通信と手動通信を同時に実行できます。これは問題になる可能性がありますか?
ありがとう。