Background Tasks in Async Methods Part 2
Silly me!
After Brian Dunnington left some comments on yesterday's post, I was very keen to get home and refactor my code using his suggestions.
On the drive home, though, it occurred to me that there was probably an even easier way to start a background task from an async method without a compiler warning, and it turns out I was right.
Simply start the background operation in a non-async method and call that from your async method.
So now my LoadFriendUserNameAsync
method is called LoadFriendUserNames
, and thanks to Brian's suggestion to use Task.Run
rather than Task.Factory.StartNew
, it's way simpler. Voila!
void LoadFriendUserNames()
{
Task.Run(async () =>
{
var friendsResponse = await Client.GetFriendIdsAsync();
if (friendsResponse.StatusCode != System.Net.HttpStatusCode.OK) return new string[0];
var usersResponse = await Client.LookupUsersAsync(friendsResponse.Result);
if (usersResponse.StatusCode != System.Net.HttpStatusCode.OK) return new string[0];
return usersResponse.Result.Select(u => u.ScreenName).ToArray();
}).ContinueWith(task =>
{
if (task.IsFaulted || task.IsCanceled) return;
foreach (var user in task.Result) UserNames.Add(user);
}, TaskScheduler.Current);
}
As you can see, there's no messing about with nested tasks or passing the current TaskScheduler
instance as a parameter to the background task. It's pretty straight forward!
So thanks Brian, and I hope this helps someone else out there!
Trackbacks
- Dew Drop – April 4, 2013 (#1,520) | Alvin Ashcraft's Morning Dew | http://www.alvinashcraft.com/2013/04/04/dew-drop-april-4-2013-1520/
No new comments are allowed on this post.
Comments
brian dunnington
Looks a lot cleaner. My helper method is exactly what you described: a non-async, void-returning method that takes a Task parameter so you can wrap any task in a generic fire-and-forget wrapper.
Off topic, but I am liking Halfwit RT and the fast pace of updates. Keep 'em coming =)