Search code examples
c#async-awaitlinq-to-twitter

awaited task not running asynchronously


I'm trying to download some twitter info asynchronously and it's blocking the UI thread. I'm using LinqToTwitter (http://linqtotwitter.codeplex.com/) to download the info.

Here's the call to the task

PublicTweetListBox.ItemsSource = await getTweets(twitterCtx);

And here's the task itself

async Task<List<TweetViewModel>> getTweets(TwitterContext twitterCtx)
{       
    var tweetList = await Task.FromResult<List<TweetViewModel>>(
    (from tweet in twitterCtx.Status
    where tweet.Type == StatusType.User
    && tweet.ScreenName == UserName.Text
    select new TweetViewModel
    {
        Name = tweet.User.Name,
        Tweet = tweet.Text,
        ImageUrl = tweet.User.ProfileImageUrl
    })
    .ToList());

    return tweetList;

}

I'm doing something wrong in the way I await downloading the list, TweetViewModel is a custom type if that helps.


Solution

  • async and await do not magically make blocking code non-blocking. Linq-to-twitter is not an asynchronous API, and sticking it in a Task.FromResult will do nothing.

    If you want to push the querying to a background thread, you could use Task.Run instead of Task.FromResult. A more efficient (but more involved) solution would be to use an asynchronous twitter API.