[英]Don't wait for Async call inside async method that is being waited on
我从异步方法中看到了一些奇怪的行为。 我最近发现,在所有Windows设备上都无法对整个zip存档进行解压缩。 如此之多,以至于我不得不提取我需要的单个文件,并在等待存档的其余部分提取时使用它。 但是,当前从同一方法调用提取单个文件的代码和提取整个档案的代码。 该方法是异步的,最终最初由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完成并且ExtractFullArchive花了很长时间之后,DownloadArchive才返回。 我需要ExtractFullArchive在DownloadArchive完成时异步执行。 我真的不在乎什么时候完成。
如果您不想等待,请不要返回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
}
当您不在乎ExtractFullArchive
何时完成时,可以启动一个新的Task
来在另一个线程上执行该方法。 使用此方法,尽管ExtractFullArchive
尚未完成,但DownloadArchive
方法完成了。 例如,这可能看起来像这样。
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));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.