Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Continuation tasks not executing in correct order

Tags:

c#

async-await

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

  • Appending .Unwrap after .ContinueWith doesn't help
  • Returning a Task of T from these methods instead of Task and assigning their result in the caller doesn't work either

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

Sequencing tasks :

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;

Sample of executed methods :

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

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 ?

like image 358
aybe Avatar asked Dec 07 '25 23:12

aybe


1 Answers

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

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

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.

like image 143
Reed Copsey Avatar answered Dec 10 '25 12:12

Reed Copsey