0

How get result back from async method ?

 async Task<string> Get(string Url) { HttpClient httpClient = new HttpClient(); httpClient.MaxResponseContentBufferSize = 10485760; httpClient.DefaultRequestHeaders.Add("user-agent", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)"); HttpResponseMessage response = await httpClient.GetAsync(Url); return await response.Content.ReadAsStringAsync(); } 

call the method

var a = Get(address).Result; Outbox.Text = a; 

when try to get result, in output winodow i got "The thread 0xdf4 has exited with code 0 (0x0)"

and nothing happend

but i can get result by this way

 async Task Get(string Url) { HttpClient httpClient = new HttpClient(); httpClient.MaxResponseContentBufferSize = 10485760; httpClient.DefaultRequestHeaders.Add("user-agent", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)"); HttpResponseMessage response = await httpClient.GetAsync(Url); Outbox.Text = response.Content.ReadAsStringAsync().Result; } 

and call the method by this way

var a = Get(address); 

i try this code on windows phone 8.1. thanks.

1 Answer 1

2

In most cases, when calling an async method, you're supposed to await it:

var a = await Get(address); Outbox.Text = a; 

Calling .Result is technically valid, but you're freezing the calling thread, which may sometimes result in a deadlock (like in your sample).

Sign up to request clarification or add additional context in comments.

2 Comments

i try this before, the 'await' operator can only be used within an async method
Which simply means that you need to add the async keyword on your method signature. For instance if you have public void Button_Click(...), change it to public async void Button_Click(...)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.