Question

I have code to read a response from an ASP.NET Web API, like so:

HttpClient client = new HttpClient();
client.GetAsync(path.ToAbsoluteUrl()).ContinueWith(
                    (requestTask) =>
                    {
                        HttpResponseMessage response = requestTask.Result;
                        response.EnsureSuccessStatusCode();
                        response.Content.ReadAsAsync<DBResult>().ContinueWith(
                                                            (readTask) =>
                                                            {
                                                                result = readTask.Result;
                                                                lblMessage.Text = string.Format("{0} products were uploaded successfully. {1} failed.", result.Success, result.Failed);
                                                            });
                    });

I'm trying to display a message of some sort when I get the response/result back. Nothing seems to work, though - my label doesn't update.

Clearly, I'm doing something wrong - how can I display a message back to the user after the response is received?

TIA

Edit:

As suggested below, I declared:

TaskScheduler scheduler = TaskScheduler.FromCurrentSynchronizationContext();

and passed in "scheduler" (tried with both ContinueWiths), but still, nothing seems to work. Actually, now my breakpoint on lblMessage.Text... isn't reached.

Was it helpful?

Solution

It looks like you have to get to the UI thread in order to update the UI. When just running ContinueWith you can end up on eny thread. The way around this is to pass in the synchronization context using

TaskScheduler.FromCurrentSynchronizationContext();

as described in this article on MSDN [1]

Otherwise you code looks fine.

Hope this helps,

Henrik

[1] http://msdn.microsoft.com/en-us/library/dd997394.aspx

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top