Search code examples
c#windows-phone-7httpwebrequestnullreferenceexceptiongetresponsestream

NullReferenceException reading from an asynchronous HttpWebRequest stream


I'm programming an application for Windows Phone 7. This application firstly sends, and then receives data from a server via HttpWebRequest. Most times it works fine, but sometimes, after receiving a portion of the data properly, I get a NullReferenceException in Stream.Read() function.

The communication starts when the user presses a button. Then I create the HttpWebRequest:

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

The request callback method:

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
}

The response callback method:

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
}

And finally, this is the code where I get the exception reading the stream data:

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

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

When the application starts, I create a background thread that frequently sends info to the server. Background and Manual communications can run simultaneously. Could this be a problem?

Thanks.


Solution

  • If streamResponse is global variable, it can cause the problem in a case of an access from another thread. Pass your Stream to the Recv as a parameter

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