HTTPClient在计量连接上失败并且在wifi上正常工作

时间:2014-02-07 17:51:39

标签: c# windows-phone-8 dotnet-httpclient

我的应用程序可以正常使用WiFi但是当它通过3G连接时它会崩溃。

这是代码:

protected override async void OnNavigatedTo(NavigationEventArgs e)
{
    if (!App.ViewModel.IsDataLoaded)
    {
        await App.ViewModel.LoadDataAsync();
        DataContext = App.ViewModel;
    }
}

LoadDataAsync的代码

    public async Task<bool> LoadDataAsync()
    {
        Uri uri = new Uri("http://www.28cinema.az/eng/");
        HttpClient client = new HttpClient();
        HtmlDocument htmlDocument = new HtmlDocument();
        HtmlNode htmlNode = new HtmlNode(0, htmlDocument, 1);
        MovieGroup data = new MovieGroup();
        string HtmlResult;    
        HtmlResult = await client.GetStringAsync(uri);
        data.Title = "Today";
        htmlDocument.LoadHtml(HtmlResult);            
        htmlNode = htmlDocument.DocumentNode.SelectSingleNode("//div[@class='poster_wrapper']");

        for (var i = 0; i < (htmlNode.ChildNodes.Count); i++)
        {
            data.Items.Add(new MovieData
            {
                DetailsUrl = htmlNode.SelectSingleNode("div[" + (i + 1) + "]/div[1]/div[1]/a[1]").GetAttributeValue("href", ""),
                Title = htmlNode.SelectSingleNode("div[" + (i + 1) + "]/div[1]/div[1]/a[1]").InnerText,
                Poster = htmlNode.SelectSingleNode("div[" + (i + 1) + "]/img").GetAttributeValue("src", "No poster"),
                Cinema = "28 Cinema"
            });
        }
        Today = data;        
        IsDataLoaded = true;
        return true;
    }

异常消息:没有网络连接,任务被取消。

堆栈追踪:

   at Cineman.ViewModels.MovieModel.<CreateTodayGroupAsync>d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at Cineman.ViewModels.MovieModel.<LoadDataAsync>d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at Cineman.MainPage.<OnNavigatedTo>d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.AsyncMethodBuilderCore.<ThrowAsync>b__0(Object state)

任何建议都将受到赞赏。

UPD:在断点期间进一步查看本地变量中的这一行:&#39; htmlNode.InnerHtml&#39;抛出类型&#39; System.NullReferenceException&#39;

的例外

2 个答案:

答案 0 :(得分:0)

正如您所发现的,如果您在没有网络连接的情况下尝试执行HTTP请求,则会引发异常。

我建议您处理例外情况,例如try / catch。如何向用户显示例外详细信息取决于您。

答案 1 :(得分:0)

当我重新启动Visual Studio时它解决了。怪异!