Try-Catch没有显示带有等待的消息对话框

时间:2013-11-25 16:45:54

标签: c# windows-8 try-catch

以下代码成功从Web服务获取数据并将其显示在Windows 8桌面应用程序中。

HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync("http://localhost:12345/api/items");

var info = new List<SampleDataGroup>();

if (response.IsSuccessStatusCode)
{
    var content = await response.Content.ReadAsStringAsync();

    var item = JsonConvert.DeserializeObject<dynamic>(content);

    foreach (var data in item)
    {
        var infoSect = new SampleDataGroup
        (
            (string)data.Id.ToString(),
            (string)data.Name,
            (string)"",
            (string)data.PhotoUrl,
            (string)data.Description
        );
        info.Add(infoSect);
    }
}
else
{
    MessageDialog dlg = new MessageDialog("Error");
    await dlg.ShowAsync();
}

但是,这需要互联网连接才能工作。每次没有互联网连接时,应用程序都会崩溃。

如果网络连接不起作用,如何在此代码中编写try catch语句以显示弹出消息?

修改

我正在尝试使用下面的MessageDialog,这会阻止应用崩溃,但它不会显示消息。

     catch (Exception ex)
        {
            MessageDialog err = new MessageDialog(ex.Message);

        }

1 个答案:

答案 0 :(得分:0)

你不需要

string errorMessage = string.Empty;

try 
{

  HttpClient client = new HttpClient();
  HttpResponseMessage response = await    
  client.GetAsync("http://localhost:12345/api/items");

  var info = new List<SampleDataGroup>();

  if (response.IsSuccessStatusCode)
  {
    var content = await response.Content.ReadAsStringAsync();

    var item = JsonConvert.DeserializeObject<dynamic>(content);

    foreach (var data in item)
    {
        var infoSect = new SampleDataGroup
        (
            (string)data.Id.ToString(),
            (string)data.Name,
            (string)"",
            (string)data.PhotoUrl,
            (string)data.Description
        );
        info.Add(infoSect);
    }
  }
  else
  {
      errorMessage = "Error";
  }      
}    
catch (Exception ex)
{
  ErrorMessage = ex.Message;
}

if (errorMessage != string.Empty) 
{
  MessageDialog dlg = new MessageDialog(errorMessage);
  await dlg.ShowAsync();
}