如何确保UploadStringCompletedEventHandler事件已成功执行?

时间:2014-02-10 10:40:36

标签: post windows-phone-8 webclient uploadstring

如何确保UploadStringCompletedEventHandler事件已成功执行?在下面的代码中你可以看到我调用函数UploadMyPOST,其lastreads参数包含一些数据。现在您可以看到我将名为response的变量保存到MyClassXYZ varialbe中。在最后,您可以看到有一个事件由方法调用UploadMyPost()将服务器响应填充到响应变量中。现在这里的问题是UploadMyPost(lastreads)成功执行但是它的被调用事件没有执行。甚至游标也不会继续执行该事件,因为我无法将服务器响应填充到响应变量中。所以任何人都知道我可以等到该事件成功执行的任何方法,我能够保存服务器响应吗?

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)
   {
   }
 }

//在Stephen Sugge之后我使用了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;
   }

2 个答案:

答案 0 :(得分:2)

我建议您使用HttpClientwrap the UploadStringAsync/UploadStringCompleted pair into a Task-based method。然后,您可以在await中使用MyMethod。{/ p>

答案 1 :(得分:0)

谢谢你Stephen Clear你带领我朝着正确的方向前进,我使用HttpClient成功发布了我的请求。

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;