【发布时间】:2021-05-05 08:50:42
【问题描述】:
我有这个功能,最多可以输入 10 个项目作为输入列表
public async Task<KeyValuePair<string, bool>[]> PayCallSendSMS(List<SmsRequest> ListSms)
{
List<Task<KeyValuePair<string, bool>>> tasks = new List<Task<KeyValuePair<string, bool>>>();
foreach (SmsRequest sms in ListSms)
{
tasks.Add(Task.Run(() => SendSMS(sms)));
}
var result = await Task.WhenAll(tasks);
return result;
}
在这个函数中,我 await 用于下载一些 JSON,并在完成反序列化后对其进行反序列化。
public async Task<KeyValuePair<string, bool>> SendSMS(SmsRequest sms)
{
//some code
using (WebResponse response = webRequest.GetResponse())
{
using (Stream responseStream = response.GetResponseStream())
{
StreamReader rdr = new StreamReader(responseStream, Encoding.UTF8);
string Json = await rdr.ReadToEndAsync();
deserializedJsonDictionary = (Dictionary<string, object>)jsonSerializer.DeserializeObject(Json);
}
}
//some code
return GetResult(sms.recipient);
}
public KeyValuePair<string, bool> GetResult(string recipient)
{
if (deserializedJsonDictionary[STATUS].ToString().ToLower().Equals("true"))
{
return new KeyValuePair<string, bool>(recipient, true);
}
else // deserializedJsonDictionary[STATUS] == "False"
{
return new KeyValuePair<string, bool>(recipient, false);
}
}
我的问题是在return GetResult(); 部分,其中deserializedJsonDictionary 为空(并且因为json 还没有完成下载)。
但我不知道如何解决它
我尝试使用ContinueWith,但它对我不起作用。
我愿意接受对我的原始代码和/或解决方案设计的任何更改
【问题讨论】:
-
你为什么使用
WebRequest? (WebRequest是古老的,不应使用)。为什么不使用支持 real 异步 IO 的HttpClient?您也不应该为此使用Task.Run。 -
if (deserializedJsonDictionary[STATUS].ToString().ToLower().Equals("true")) -
deserializedJsonDictionary不为空“因为 JSON 尚未完成下载” - 这是因为您错误地反序列化 JSON。您需要查看实际的响应正文(请将其发布在您的问题中,以便我们查看)。Newtonsoft.Json库非常宽容,默认情况下,如果 JSON 文本与请求的类型不匹配,它将返回null而不是抛出描述性异常。
标签: c# json async-await task streamreader