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!

c# async
Posted by: Matt Hamilton
Last revised: 18 Jan, 2017 03:49 AM History



04 Apr, 2013 02:51 PM

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

No new comments are allowed on this post.