2014-02-10 54 views
0

如何確保UploadStringCompletedEventHandler事件已成功執行?在下面的代碼中,你可以看到我正在使用我的lastreads參數調用函數UploadMyPOST,它有一些數據。現在你可以看到我正在將一個名爲response的變量保存到MyClassXYZ varialbe中。在極端情況下,您可以看到有一個事件由UploadMyPost()方法調用,將服務器響應填充到響應變量中。現在這裏的問題是UploadMyPost(lastreads)成功執行,但其調用的事件不會執行。即使光標不會繼續發生,我無法將服務器響應填充到響應變量中。所以,任何人都知道我可以等待,直到該事件成功執行的任何方法,我可以保存服務器響應?如何確保UploadStringCompletedEventHandler事件已成功執行?

private async void MyMethod(MyClassXYZ lastreads) 
{ 
    await UploadMyPOST(lastreads); 
    MyClassXYZ serverResponse = response; 
    if (serverResponse.Book == null) 
    { 
      //Do Something. 
    } 
} 

private void UploadMyPOST(MyClassXYZ lastreads) 
{ 
    apiData = new MyClassXYZApi() 
    { 
     AccessToken = thisApp.currentUser.AccessToken, 
     Book = lastreads.Book, 
     Page = lastreads.Page, 
     Device = lastreads.Device 
    }; 
    //jsondata is my global variable of MyClassXYZ class. 
    jsondata = Newtonsoft.Json.JsonConvert.SerializeObject(apiData); 
    MyClassXYZ responsedData = new MyClassXYZ(); 
    Uri lastread_url = new Uri(string.Format("{0}lastread", url_rootPath)); 
    WebClient wc = new WebClient(); 
    wc.Headers["Content-Type"] = "application/json;charset=utf-8"; 
    wc.UploadStringCompleted += new UploadStringCompletedEventHandler(MyUploadStringCompleted); 
    wc.UploadStringAsync(lastread_url, "POST", jsondata); 
} 

private void MyUploadStringCompleted(object sender, UploadStringCompletedEventArgs e) 
{ 
    try 
    { 
     if (e.Error == null) 
     { 
      string resutls = e.Result; 
      DataContractJsonSerializer json = new DataContractJsonSerializer(typeof(MyClassXYZ)); 
      MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(resutls)); 
      response = (MyClassXYZ)json.ReadObject(ms); 
     } 
     else 
     { 
      string sx = e.Error.ToString(); 
     } 
    } 
    catch(Exception exe) 
    { 
    } 
} 

//斯蒂芬suggession後,我使用HttpClient的,所以我已經寫新代碼的HttpClient的幫助。代碼正在成功構建,但是在運行時,光標從此方法退出到其調用的父方法。

private async Task<string> UploadMyPOST(MyClassXYZ lastreads) 
    { 
     string value = ""; 
     try 
     { 
      apiData = new LastReadAPI() 
      { 
       AccessToken = thisApp.currentUser.AccessToken, 
       Book = lastreads.Book, 
       Page = lastreads.Page, 
       Device = lastreads.Device 
      }; 
      jsondata = Newtonsoft.Json.JsonConvert.SerializeObject(apiData); 
      LastRead responsedData = new LastRead(); 
      Uri lastread_url = new Uri(string.Format("{0}lastread", url_rootPath)); 
      HttpClient hc = new HttpClient(); 

      //After following line cursor go back to main Method. 
      var res = await hc.PostAsync(lastread_url, new StringContent(jsondata)); 
      res.EnsureSuccessStatusCode(); 
      Stream content = await res.Content.ReadAsStreamAsync(); 
      return await Task.Run(() => Newtonsoft.Json.JsonConvert.SerializeObject(content)); 
      value = "kd"; 
     } 
     catch 
     { } 
     return value; 
    } 

回答

0

謝謝斯蒂芬清除你引導我在一個正確的方向,我確實使用HttpClient POST我的請求。

HttpClient hc = new HttpClient(); 
hc.BaseAddress = new Uri(annotation_url.ToString()); 
HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Post, myUrl); 
HttpContent myContent = req.Content = new StringContent(myJsonData, Encoding.UTF8, "application/json"); 
var response = await hc.PostAsync(myUrl, myContent); 

//Following line for pull out the value of content key value which has the actual resposne. 
string resutlContetnt = response.Content.ReadAsStringAsync().Result; 
DataContractJsonSerializer deserializer_Json = new DataContractJsonSerializer(typeof(MyWrapperClass)); 
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(resutlContetnt.ToString())); 
AnnotateResponse = deserializer_Json.ReadObject(ms) as Annotation; 
2

我建議您使用HttpClientwrap the UploadStringAsync/UploadStringCompleted pair into a Task-based method。然後你可以使用await像你想要的MyMethod

+0

Hi @Stephen Clery, 現在我正在使用WebClient的HttpClient inplace。通過使用它,代碼正在成功構建,但在特定行上,當我使用try catch塊時,遊標返回到我的父級方法。我發佈代碼,現在我正在更新我正在使用的代碼。 –

+0

yes現在光標正在執行成功。這是我的錯誤,我正在調用函數而不用等待關鍵字,現在執行這個函數。在res.EnsureSuccessStatusCode()我得到異常401.請看看我錯了嗎? –

+0

HTTP 401是「未經授權」 –

相關問題