Ema*_*rsa 0 c# asynchronous exception async-await
documents是IDictionary<string, string>参数的位置<filename, fileUrl>
DocumentHandler.Download() 返回一个 Task<Memorystram>
此代码有效:
foreach (var x in documents.Keys)
{
var result = await DocumentHandler.Download(new Uri(documents[x]));
// other code
}
Run Code Online (Sandbox Code Playgroud)
然而它同步发展.
为了运行它所有async我写了这段代码:
var keys =
documents.Keys.Select(async x =>
{
return Tuple.Create(x, await DocumentHandler.Download(new Uri(documents[x])));
});
await Task.WhenAll(keys);
foreach (var item in keys)
{
var tpl = item.Result;
// other code
}
Run Code Online (Sandbox Code Playgroud)
它不起作用,它崩溃而没有在最后一行显示异常var tpl = item.Result;为什么?
每次评估时,您的keys变量都会创建一组新任务...因此,在等待第一组任务完成后,您将迭代一组新的未完成任务.对此的简单修复是添加一个调用ToList():
var keys = documents
.Keys
.Select(async x => Tuple.Create(x, await DocumentHandler.Download(new Uri(documents[x]))))
.ToList();
await Task.WhenAll(keys);
foreach (var item in keys)
{
var tpl = item.Result;
// other code
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
123 次 |
| 最近记录: |