2

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-

アプリケーションが起動すると、サーバーに情報を頻繁に送信するバックグラウンドスレッドを作成します。バックグラウンド通信と手動通信を同時に実行できます。これは問題になる可能性がありますか?

ありがとう。

4

3 に答える 3

1

がグローバル変数の場合streamResponse、別のスレッドからのアクセスの場合に問題が発生する可能性があります。パラメータとしてにStreamを渡すRecv

using (StreamReader streamResponse = new StreamReader(response.GetResponseStream() ) )
{
  this.bSyncOK = Recv(streamResponse); //This is my generic method to receive the data
  streamResponse.Close();
}
于 2011-12-29T13:02:11.540 に答える
0

streamResponse後者のスニペットで宣言されているのはどこですか?3Dスニペットと同じオブジェクトですか?実際のストリームの代わりに、別の変数を使用するだけかもしれません。

于 2011-12-29T12:37:11.167 に答える
0

2番目のスニペットで、「postStream.Close();」を削除してみてください。

于 2011-12-30T06:05:37.310 に答える