HttpClient GetAsync在Windows 8上没有完成非void返回类型

时间:2012-11-04 20:45:43

标签: c# asynchronous windows-8 windows-runtime

我正在尝试使用Windows 8应用的异步功能下载和解析网站。

我用这种方法调用下载代码:

private async Task<Show> getSeasonAndEpisodeInformation(Show currentShow)
    {
        int seriesID = currentShow.SeriesID;
        EpisodeBuilder epBuilder = new EpisodeBuilder(seriesID);

        List<Episode> eps = await epBuilder.getEpisodeList();
        SeasonBuilder seasonBuilder = new SeasonBuilder(eps);

        return currentShow;
    }

getEpisodeList()函数是:

public async Task<List<Episode>> getEpisodeList()
    {
        httpClient = new HttpClient();
        httpClient.MaxResponseContentBufferSize = 2560000;
        httpClient.DefaultRequestHeaders.Add("user-agent", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)");

        try
        {
            List<Episode> episodes = new List<Episode>();
            HttpResponseMessage response = await httpClient.GetAsync(new Uri("http://www.example.com"));
            response.EnsureSuccessStatusCode();
            //Never get here

            return episodesList;
        }
        catch (Exception)
        {

        }

        return null;
    }

如果我的getEpisodeList方法无效,那么网页将下载并继续。我已经调试并确保它是永远不会完成的httpClient.GetAsync(..)行。反正有吗?

在getSeasonAndEpisodeInformation方法中,我需要确保在继续之前返回了getEpisodeList()方法 - 因此在调用epBuilder.getEpisodeList()时使用了await关键字。

2 个答案:

答案 0 :(得分:0)

您发布的所有代码都很好。您可能正在调用树的某个地方调用Task.WaitTask.Result。正如我在博客中描述的那样this will cause a deadlock

要解决此问题,请移除对WaitResult的所有来电。完全使用“await”。

答案 1 :(得分:0)

我通过在调用http.GetAsync时删除“await”关键字来修复此问题。调用现在完成,getSeasonAndEpisodeInformation方法中的'await'确保它以异步方式运行。