![](/img/trans.png)
[英]System.AggregateException: One or more errors occurred. ---> System.Web.Services.Protocols.SoapException
[英]Sync and Async problem. System.aggregateexception 'one or more errors occurred.' when I try to get a list of objects from an URL
所以,我试图从 tmdb 获取一个包含电影列表的 json,为此我在此处创建了方法。 问题是,如果同步运行它会给我超时。
public void getMovieInfo(string kWord)
{
using (WebClient web = new WebClient())
{
string url = string.Format("https://api.themoviedb.org/3/search/movie?page=1&api_key=" + apiKey + "&query=" + kWord);
var json = web.DownloadString(url);
var result = JsonConvert.DeserializeObject<JsonExtract.root>(json);
JsonExtract.root outPut = result;
movies.Clear();
int accesIndex = 0;
while (outPut.results != null)
{
movies.Add(outPut.results[accesIndex++].title);
}
}
}
如果我返回一个 Task.Result
public async Task<string> getMovieInfoAsync(string kWord)
{
using (WebClient web = new WebClient())
{
string url = string.Format("https://api.themoviedb.org/3/search/movie?page=1&api_key=" + apiKey + "&query=" + kWord);
var json = web.DownloadString(url);
var result = JsonConvert.DeserializeObject<JsonExtract.root>(json);
JsonExtract.root outPut = result;
movies.Clear();
int accesIndex = 0;
while (outPut.results != null)
{
movies.Add(outPut.results[accesIndex++].title);
}
}
像这样调用它可以工作,但在第一次调用时会冻结 3 秒
getMovieInfoAsync(keyword);
如果这样的调用它会给我“System.aggregateexception”一个或多个错误发生。
Task<string> task = Task.Run(async () => await getMovieInfoAsync(keyword));
task.Wait();
movies = task.Result;
我已经搜索并尝试了很多小时的解决方案,但还没有成功。 sameone 可以给我任何关于为什么会发生这种情况的指示,或者可以向我解释我做错了什么。 谢谢
简单地返回Task
不会使您的方法异步。
这样做:
var json = web.DownloadString(url);
仍然会阻塞线程,直到您收到 HTTP 响应。
WebClient
是一种预异步技术, DownloadString
是一种同步方法。
我会看看HttpClient
,它有更好的异步支持:
using (HttpClient client = new HttpClient())
using (HttpResponseMessage response = await client.GetAsync(url))
{
string json = await response.Content.ReadAsStringAsync();
}
使用async
关键字将释放线程,直到您得到响应。
您使用Task.Run
第二个示例是一种Task.Run
的解决方法,但如果您检查内部异常,您应该有一个更好的主意。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.