一直尝试按顺序执行任务,但它们是以随机顺序执行的。
- 在 .ContinueWith 之后附加 .Unwrap 没有帮助
- 从这些方法而不是 Task 返回 T 的 Task 并将其结果分配给调用者也不起作用
不确定我的方法的签名,它们是否应该包含 async/await 。
排序任务:
Task biographies = LoadArtistBiographies(apiKey);
Task blogs = LoadArtistBlogs(apiKey);
Task familiarity = LoadArtistFamiliarity(apiKey);
Task hottness = LoadArtistHottness(apiKey);
Task images = LoadArtistImages(apiKey);
await biographies.ContinueWith(b => blogs);
await blogs.ContinueWith(f => familiarity);
await familiarity.ContinueWith(h => hottness);
await hottness.ContinueWith(i => images);
await images;
执行方法的示例:
private async Task LoadArtistBiographies(string apiKey)
{
var parameters = new ArtistBiographiesParameters();
parameters.SetDefaultValues();
parameters.ApiKey = apiKey;
parameters.Id = _artistId;
ArtistBiographies biographies = await Queries.ArtistBiographies(parameters);
ItemsControlBiographies.ItemsSource = biographies.Biographies;
}
Queries.* 方法也是异步的:
public static async Task<ArtistBlogs> ArtistBlogs(ArtistBlogsParameters parameters)
链接任务本身正在执行异步任务的正确语法是什么?
如果您想按特定顺序执行任务,您应该await
他们直接:
await LoadArtistBiographies(apiKey);
await LoadArtistBlogs(apiKey);
await LoadArtistFamiliarity(apiKey);
await LoadArtistHottness(apiKey);
await LoadArtistImages(apiKey);
这将导致第二个任务(LoadArtistBlogs
)在第一个任务完成后安排。
现在,任务正在“以随机顺序”执行,因为您已将它们分配给Task
实例,这允许每个实例同时执行。
话虽这么说,我实际上建议更改您的方法以返回值,而不是将它们分配给方法内的数据源:
private async Task<Biographies> LoadArtistBiographiesAsync(string apiKey)
{
var parameters = new ArtistBiographiesParameters();
parameters.SetDefaultValues();
parameters.ApiKey = apiKey;
parameters.Id = _artistId;
var bio = await Queries.ArtistBiographies(parameters);
return bio.Biographies;
}
然后你可以将它们写为:
ItemsControlBiographies.ItemsSource = await LoadArtistBiographiesAsync(apiKey);
// Other methods below, with await as this example
在我看来,这使得逻辑流经异步方法的意图更加清晰。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)