I'm fetching data from a service through use of an async method:
var activityList = await Task.Run(() => dataService.GetActivitiesAsync());
But for each activity I still need to load Athlete data. So now I just loop the activities and load up the athlete data like so ( there is no bulk load option for athlete ):
foreach(var activity in activityList)
{
activity.Athlete = dataService.GetAthleteAsync(activity.AthleteID);
}
But this GetAthleteAsync will also return a Task, so I was just wondering isn't there a better way to get this done in a background thread? Somehow with Task.WhenAll or anything else? The Athlete property on the Activity object has NotifyPropertyChanged so the UI will show the needed data when it's set. The GetAthleteAsync method will already try to cache athletes based on the given id.
Any suggestions on how to make this perform better?
Some details, all methods are connecting to a web API. Mostly we'll be targetting 10 unique Athletes ( but depending on the user, this could increase ).
Hms, if dataService.GetActivitiesAsync()
is async and everything is called from the UI-thread, what you can do is this:
// no wrapping in Task, it is async
var activityList = await dataService.GetActivitiesAsync();
// Select a good enough tuple
var results = (from activity in activityList
select new {
Activity = activity,
AthleteTask = dataService.GetAthleteAsync(activity.AthleteID)
}).ToList(); // begin enumeration
// Wait for them to finish, ie relinquish control of the thread
await Task.WhenAll(results.Select(t => t.AthleteTask));
// Set the athletes
foreach(var pair in results)
{
pair.Activity.Athlete = pair.AthleteTask.Result;
}
(Written of the top of my head, ie no syntax checking, so some method calls could be wrong)