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是全局变量,则在从另一个线程访问的情况下可能会导致问题。将您作为参数传递StreamRecv

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

在第二个片段中,尝试删除“postStream.Close();”。

于 2011-12-30T06:05:37.310 回答