小编Kri*_*Oye的帖子

完成c#任务再次运行......为什么?

我对我的代码[下面]的行为感到有点困惑.我正在开发一个专门的命令行实用程序,可以下载和处理一些文件.我想尽可能使用c#的异步功能.创建任务并使用Task.WaitAll()时,代码段按预期运行.在等待之后,我有2个任务,这两个任务都被标记为已完成.问题:我尝试从任务中获取结果最终会再次运行这两个任务!为什么是这样?如何在不执行第二次任务的情况下读取结果?

    private IEnumerable<Task<FileInfo>> DownloadFiles()
    {
        int fileCount = 1;

        Console.Clear();
        Console.SetCursorPosition(0, 0);
        Console.Write("Download files...");

        yield return DownloadFile(Options.SkuLookupUrl, "SkuLookup.txt.gz", fileCount++, f =>
        {
            return DecompressFile(f);
        });
        yield return DownloadFile(Options.ProductLookupUrl, "ProductList.txt.gz", fileCount++, f =>
        {
            return DecompressFile(f);
        });
    }

    public void Execute()
    {
        var tasks = DownloadFiles();
        Task.WaitAll(tasks.ToArray());

        Console.WriteLine();
        Console.WriteLine("Download(s) completed.  Parsing sku lookup file.");
        FileInfo[] files = tasks.Select(t => t.Result).ToArray(); // <-- triggers a second round of task execution

        ParseSkuLookups(files.SingleOrDefault(f => f.Name.ToLowerInvariant().Contains("skulookup")));
    }
Run Code Online (Sandbox Code Playgroud)

如果相关的是下载方法:

    private async Task<FileInfo> DownloadFile(string targetUrl, string destinationFile, …
Run Code Online (Sandbox Code Playgroud)

c# async-await c#-4.0

4
推荐指数
1
解决办法
131
查看次数

标签 统计

async-await ×1

c# ×1

c#-4.0 ×1