2013-06-25 146 views
0

我正在使用以下代碼將數據從windows phone 8發送到服務器。如何知道什麼時候異步post請求已完成WP8

responseString即將成爲默認值。

但是,如果幾秒鐘後檢查,它會被更新。

有什麼辦法,當請求完成

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Net; 
using System.Windows; 
using System.Windows.Controls; 
using System.Windows.Navigation; 
using Microsoft.Phone.Controls; 
using Microsoft.Phone.Shell; 
using System.IO; 
using System.Text; 

namespace Blood_Bank 
{ 
    public partial class Page1 : PhoneApplicationPage 
    { 
     String responseString = "amit"; 
     public event Action Completed; 
     StringBuilder postData = new StringBuilder(); 
     public Page1() 
     { 
      InitializeComponent(); 
     } 


     private void submit_Click(object sender, RoutedEventArgs e) 
     { 
      // Create a new HttpWebRequest object 
      HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.mywindowsproject.appspot.com"); 

      // request.ContentType = "text/html"; 

      // Set the Method property to 'POST' to post data to the URI. 
      request.Method = "POST"; 

      // start the asynchronous operation 

      postData.Append("name=" + name.Text.ToString()+"&"); 


      request.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), request); 


       MessageBox.Show(responseString);   

     } 
     private void GetRequestStreamCallback(IAsyncResult asynchronousResult) 
     { 

      HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState; 

      // End the operation 
      Stream postStream = request.EndGetRequestStream(asynchronousResult); 


      // Convert the string into a byte array. 
      byte[] byteArray = Encoding.UTF8.GetBytes(postData.ToString()); 

      // Write to the request stream. 
      postStream.Write(byteArray, 0, postData.Length); 
      postStream.Close(); 

      // Start the asynchronous operation to get the response 
      request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request); 
     } 
     private void GetResponseCallback(IAsyncResult asynchronousResult) 
     { 
      HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState; 

      // End the operation 

      try 
      { 


       HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult); 
       Stream streamResponse = response.GetResponseStream(); 
       StreamReader streamRead = new StreamReader(streamResponse); 
       responseString = streamRead.ReadToEnd(); 

       streamResponse.Close(); 
       streamRead.Close(); response.Close(); 
       if (Completed != null) 
        Completed(); 

      } 
      catch (WebException e) 
      { 

      } 
     } 
    } 
} 

回答

1

您已經到位的方法的請求完成時被調用就知道了。在你的方法GetResponseCallback中,你應該有更新的responseString。您可以在該方法中引發事件,以便其他類可以處理更新responseString,或處理方法本身內的邏輯。

另請參閱此introduction to event based programming in C#

相關問題