문제

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.

도움이 되었습니까?

해결책

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top