【问题标题】:Don't wait for Async call inside async method that is being waited on不要在正在等待的异步方法中等待异步调用
【发布时间】:2016-03-26 14:51:09
【问题描述】:

我从我的异步方法中看到了一些奇怪的行为。我最近发现解压缩我的整个 zip 存档在所有 Windows 设备上都不是高效的。如此之多,以至于我不得不提取我需要的单个文件,在等待其余存档提取时使用它。但是,目前提取单个文件的代码和提取整个档案的代码是从同一方法调用的。此方法是异步的,最终最初由 App.xaml.cs 中的代码在 UI 线程上调用。当我调用此方法时,我使用 await 关键字等待它完成,因为 zip 存档中有一个文件我需要加载应用程序。

App.xaml 如下所示:

SharedContext.ChangeUniverse("1234");

SharedContext 如下所示:

public static void ChangeUniverse(string universe) {
    await DownloadArchive(universe);
}

public async Task DownloadArchive(string universe) {
    ZipArchive archive = magic; // get it somehow
    var someLocalFilePath = magic; // the exact location I need to extract data.json
    var someLocalPath = magic; // the exact location I need to extract the zip
    archive.GetEntry("data.json").ExtractToFile(someLocalFilePath);
    // notice I do NOT await
    ExtractFullArchive(archive, someLocalPath);
}

public async Task ExtractFullArchive(ZipArchive archive, string path) {
    archive.ExtractToDirectory(path, true); // extracting using an override nice extension method I found on SO.com
}

问题在于,在 ExtractFullArchive 完成之前,DownloadArchive 不会返回,而 ExtractFullArchive 需要很长时间。我需要 ExtractFullArchive 在 DownloadArchive 完成时异步执行。我真的不在乎什么时候结束。

【问题讨论】:

  • ExtractToDirectory真的是异步方法吗?

标签: c# multithreading xaml asynchronous win-universal-app


【解决方案1】:

当您不关心ExtractFullArchive 何时结束时,您可以启动一个新的Task 以在另一个线程上执行该方法。通过这种方法,DownloadArchive 方法完成,尽管 ExtractFullArchive 尚未完成。例如,这可能看起来像这样。

public async Task DownloadArchive(string universe) {
    ZipArchive archive = magic; // get it somehow
    var someLocalFilePath = magic; // the exact location I need to extract data.json
    var someLocalPath = magic; // the exact location I need to extract the zip
    archive.GetEntry("data.json").ExtractToFile(someLocalFilePath);
    Task.Run(() => ExtractFullArchive(archive, someLocalPath));
}

【讨论】:

    【解决方案2】:

    如果您不想等待,请不要返回 Task,而是像这样返回 void

    public async void ExtractFullArchive(ZipArchive archive, string path) {
        archive.ExtractToDirectory(path, true); // extracting using an override nice extension method I found on SO.com
    }
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-22
    • 1970-01-01
    • 2021-06-30
    • 2016-07-07
    • 2016-03-25
    • 2017-10-09
    相关资源
    最近更新 更多