如何在Windows 10提取返回任务数据异步方法在C# [英] How to extract data from returned Tasks in an async method in c# in Windows 10

查看:141
本文介绍了如何在Windows 10提取返回任务数据异步方法在C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从 getResponseFromUrl 返回值中提取低于的foreach 数据循环:
在这里,我无法提取返回值的数据。
我建立在Windows应用程序10个通用的应用开发。

  VAR响应= NetworkingCalls.getResponseFromUrl(URL,requestDictionary);的foreach(KeyValuePair&下;串,对象>响应项)
{
     Util.debugLog(item.Key.ToString(),item.Value.ToString());
}

这是模型code返回字典

 使用系统;
使用System.Collections.Generic;
使用System.Threading.Tasks;
使用Windows.Storage.Streams;
使用Windows.Web.Http;命名空间App2.WrittenLibraries
{
    类NetworkingCalls
    {
        公共异步静态任务<&字典LT;字符串对象>> getResponseFromUrl(字符串urlString,字典<字符串对象> requestDictionary)
        {
            VAR的客户=新的HttpClient();
            乌里URL =新的URI(urlString);
            VAR requestToSend = JSONParser.getJsonString(requestDictionary);
            HTT presponseMessage响应=等待client.PostAsync(网址,新HttpStringContent(requestToSend,
                                                                                             UNI codeEncoding.Utf8,
                                                                                             应用/ JSON));
            如果(response.IsSuccessStatus code)
            {
                尝试
                {
                    VAR responseString =等待response.Content.ReadAsStringAsync();
                    client.Dispose();
                    返回JSONParser.getDictionary(responseString);
                }
                赶上(异常前)
                {
                    client.Dispose();
                    返回新字典<字符串对象>();
                }
            }
            其他
            {
                client.Dispose();
                返回新字典<字符串对象>();
            }
        }
    }
}


解决方案

您需要等待任务的异步方法:

 异步任务FooAsync()
{
    VAR响应=等待NetworkingCalls.getResponseFromUrl(URL,requestDictionary);    的foreach(KeyValuePair&下;串,对象>响应项)
    {
         Util.debugLog(item.Key.ToString(),item.Value.ToString());
    }
}

如果你方法不能是异步你可以用 task.Result 或结果 task.GetAwaiter()调用getResult()但应该是最后的手段,因为它阻塞调用线程同步,而不是异步等待。

 无效美孚()
{
    VAR响应= NetworkingCalls。
        getResponseFromUrl(URL,requestDictionary)。
        GetAwaiter()。
        调用getResult();    的foreach(KeyValuePair&下;串,对象>响应项)
    {
         Util.debugLog(item.Key.ToString(),item.Value.ToString());
    }
}

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

解决方案

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

这篇关于如何在Windows 10提取返回任务数据异步方法在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆