How to extract data from returned Tasks in an async method in c# in Windows 10 [duplicate]

我怕爱的太早我们不能终老 提交于 2019-12-08 11:58:25

问题


How to extract the data from the returned value of getResponseFromUrl in below foreach loop: Here i am unable to extract the data from returned value. I am building an app in windows 10 universal app development.

var response = NetworkingCalls.getResponseFromUrl(url, requestDictionary);

foreach (KeyValuePair<string, object> item in response)
{              
     Util.debugLog(item.Key.ToString(), item.Value.ToString());
}

This is model code which returns the dictionary

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Windows.Storage.Streams;
using Windows.Web.Http;

namespace App2.WrittenLibraries
{
    class NetworkingCalls
    {
        public async static Task<Dictionary<string, object>> getResponseFromUrl(string urlString, Dictionary<string, object> requestDictionary)
        {
            var client = new HttpClient();
            Uri url = new Uri(urlString);
            var requestToSend = JSONParser.getJsonString(requestDictionary);
            HttpResponseMessage response = await client.PostAsync(url, new HttpStringContent(requestToSend,
                                                                                             UnicodeEncoding.Utf8,
                                                                                             "application/json"));
            if (response.IsSuccessStatusCode)
            {
                try
                {
                    var responseString = await response.Content.ReadAsStringAsync();       
                    client.Dispose();
                    return JSONParser.getDictionary(responseString);
                }
                catch (Exception ex)
                {
                    client.Dispose();
                    return new Dictionary<string, object>();
                }
            }
            else
            {
                client.Dispose();
                return new Dictionary<string, object>();
            }
        }
    }
}

回答1:


You need to await the task in an async method:

async Task FooAsync()
{
    var response = await NetworkingCalls.getResponseFromUrl(url, requestDictionary);

    foreach (KeyValuePair<string, object> item in response)
    {              
         Util.debugLog(item.Key.ToString(), item.Value.ToString());
    }
}

If you're method can't be async you can get the result with task.Result or task.GetAwaiter().GetResult() but that should be a last resort as it blocks the calling thread synchronously instead of waiting asynchronously:

void Foo()
{
    var response = NetworkingCalls.
        getResponseFromUrl(url, requestDictionary).
        GetAwaiter().
        GetResult();

    foreach (KeyValuePair<string, object> item in response)
    {              
         Util.debugLog(item.Key.ToString(), item.Value.ToString());
    }
}


来源:https://stackoverflow.com/questions/30953127/how-to-extract-data-from-returned-tasks-in-an-async-method-in-c-sharp-in-windows

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!