0

如何确保 UploadStringCompletedEventHandler 事件已成功执行?在下面的代码中,您可以看到我正在调用函数 UploadMyPOST,其中我的 lastreads 参数包含一些数据。现在您可以看到我正在将一个名为 response 的变量保存到 MyClassXYZ 变量中。在极端情况下,您可以看到 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)
   {
   }
 }

//在斯蒂芬建议之后,我使用了 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;
   }
4

2 回答 2

2

我建议您使用/HttpClient对或将其包装到基于任务的方法UploadStringAsyncUploadStringCompleted中。然后你可以await像你想要的那样使用 in MyMethod

于 2014-02-10T12:50:36.707 回答
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;
于 2014-02-13T06:29:25.887 回答