質問

How to ensure UploadStringCompletedEventHandler event has been executed successfully ? in following code you can see i am calling function UploadMyPOST with my lastreads parameter having some data. Now you can see i am saving a variable named response into the MyClassXYZ varialbe. in the extreme last you can see there is a event which invoked by the method UploadMyPost() is filling the server response into the response variable. Now here issue is UploadMyPost(lastreads) executes successfully but its invoked event does not executes. Even cursor do not go on that event by which i am not able to fill server response into the response variable. So Anyone know any approach by which i can wait until that event successfully execute and i could able to save server response ?

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

//After Stephen suggession i used the HttpClient so i have written new code with the help of HttpClient. Code is building successfully but at run time cursor goes out from this method to the parent method where from its calling.

   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

Thank you Stephen Clear you leaded me in a right direction and i did POST my request successfully using 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;

他のヒント

I recommend that you use HttpClient or wrap the UploadStringAsync/UploadStringCompleted pair into a Task-based method. Then you can use await like you want to in MyMethod.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top