AKD
AKD

Reputation: 3966

Task<T> freezing UI thread

my block of code:

Dispatcher.BeginInvoke(() => {
            var Users = GetUsers().Result;
            // proceed...
        }

private Task<List<User>> GetUsers()
{   
    var tcs = new TaskCompletionSource<List<User>>();
    wbclient.DownloadStringCompleted += (o, e) => {
                if (e.Error == null)
                    tcs.SetResult(JsonConvert.DeserializeObject<List<User>>(e.Result));
                else
                    tcs.TrySetException(e.Error);
                };
    wbclient.DownloadStringAsync(someUri);
    return tcs.Task;
}

I want to get all the users before proceeding further. So I am calling the GetUser method in a dispatcher. I just want to wait until the DownloadStringCompleted event occurs and then return. But with the above code the UI freezes. Any help is appreciated.

Note:

I'm using windows-phone 7, which does not supports async await

Upvotes: 2

Views: 529

Answers (2)

Stefan Wexel
Stefan Wexel

Reputation: 1154

You CAN use async await on Windows Phone 7, you just have to install this nuget packet to all of your projects in your solution. Works perfectly even when some projects are shared with Windows Phone 8 or some projects are portable class libraries. Very helpful.

So you should then be able to use: var Users = await GetUsers();

And by the way, you could always use HttpClient instead of WebClient : http://nuget.org/packages/Microsoft.Net.Http/2.1.10

Upvotes: 1

Darin Dimitrov
Darin Dimitrov

Reputation: 1038850

You should use a continuation and remove the Dispatcher.BeginInvoke call and the .Result call in your main thread which is blocking:

GetUsers().ContinueWith(t => 
{
    List<User> users = t.Result;
    this.TextBlock1.Text = "Complete"; 
}, TaskScheduler.FromCurrentSynchronizationContext());

Notice how I have used the TaskScheduler.FromCurrentSynchronizationContext() call in the continuation to ensure that this continuation is marshaled on the main UI thread.

Upvotes: 3

Related Questions