本文介绍了继续任务执行顺序不正确的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

曾经尝试顺序执行任务,但是它们以随机顺序执行.

Been trying to execute tasks sequentially but they are executed in a random order instead.

  • 在.ContinueWith之后附加.unwrap并没有帮助
  • 从这些方法而不是Task中返回T的Task并将其结果分配给调用者也不起作用

不确定我的方法是否签名,是否应该包含异步/等待.

Not sure about signature of my methods, whether they should contain async/await or not.

排序任务:

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.*方法也是异步的:

The Queries.* methods are also asynchronous :

public static async Task<ArtistBlogs> ArtistBlogs(ArtistBlogsParameters parameters)

链接本身正在执行异步任务的任务的正确语法是什么?

What is the correct syntax for chaining tasks that themselves are executing asynchronous tasks ?

推荐答案

如果要按特定顺序执行任务,则应直接等待:

If you want to execute the tasks in a specific order, you should await them directly:

await LoadArtistBiographies(apiKey);
await LoadArtistBlogs(apiKey);
await LoadArtistFamiliarity(apiKey);
await LoadArtistHottness(apiKey);
await LoadArtistImages(apiKey);

这将导致在第一个任务完成后安排第二个任务( LoadArtistBlogs ).

This will cause the second task (LoadArtistBlogs) to be scheduled after the first task completes.

现在,这些任务正在随机执行",因为您已将它们分配给 Task 实例,从而允许每个任务同时执行.

Right now, the tasks are executing "in random order" because you've assigned them to Task instances, which allows each to be executed simultaneously.

话虽如此,我实际上建议您将方法更改为返回值,而不是将它们分配给方法内的数据源:

That being said, I would actually recommend changing your methods around to returning the values, instead of assigning them to the datasource within the method:

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;
}

然后您可以将它们写为:

You could then write these as:

ItemsControlBiographies.ItemsSource = await LoadArtistBiographiesAsync(apiKey);
// Other methods below, with await as this example

在我看来,这使逻辑流经异步方法的意图更加明确.

This makes the intent as the logic flows through the async methods a bit more clear, in my opinion.

这篇关于继续任务执行顺序不正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-17 17:36
查看更多