如何在 Windows 10 中使用 c# 中的异步方法从返回的任务中提取数据

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

如何从 foreach 循环下面的 getResponseFromUrl 的返回值中提取数据: 在这里我无法从返回值中提取数据。 我正在 windows 10 通用应用程序开发中构建一个应用程序。

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

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

这是returns字典

的模型代码
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>();
            }
        }
    }
}

您需要 await async 方法中的任务:

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());
    }
}

如果您的方法不能 async,您可以使用 task.Resulttask.GetAwaiter().GetResult() 获得结果,但这应该是最后的手段,因为它会同步阻塞调用线程而不是异步等待:

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());
    }
}