简体   繁体   English

C#等待的问题

[英]C# awaitable problems

documents is a IDictionary<string, string> where the parameters are <filename, fileUrl> documentsIDictionary<string, string> ,其中参数为<filename, fileUrl>

DocumentHandler.Download() returns a Task<Memorystram> DocumentHandler.Download()返回Task<Memorystram>

This code works: 此代码有效:

foreach (var x in documents.Keys)
    {
        var result = await DocumentHandler.Download(new Uri(documents[x]));
        // other code
    }

however it rund synchronously. 但是它同步运行。

In order to run it all async i wrote this code: 为了运行所有异步代码,我编写了以下代码:

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
}

It doesn't work, it crashes without showing an exception on the last line var tpl = item.Result; 它不起作用,它崩溃而没有在最后一行显示异常var tpl = item.Result; Why? 为什么?

Your keys variable will create a new set of tasks every time you evaluate it... so after waiting for the first set of tasks to complete, you're iterating over a new set of unfinished tasks. 您的keys变量每次对其进行评估时都会创建一组的任务...因此,在等待第一组任务完成后,您将遍历一组新的未完成的任务。 The simple fix for this is to add a call to ToList() : 一个简单的解决方法是添加对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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM