从Windows Phone中的异步方法获取结果

时间:2015-04-17 14:32:57

标签: c# windows-phone-8.1

如何从异步方法中获取结果?

    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();
    }

调用方法

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

当试图得到结果时,我得到输出winodow “线程0xdf4已退出,代码为0(0x0)”

并没有发生任何事情

但我可以通过这种方式得到结果

    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;
    }

并通过这种方式调用方法

var a = Get(address);

我在Windows Phone 8.1上尝试此代码。 感谢。

1 个答案:

答案 0 :(得分:2)

在大多数情况下,当调用异步方法时,您应该等待它:

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

调用.Result在技术上是有效的,但是你要冻结调用线程,这有时会导致死锁(就像你的样本中一样)。