问题
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