确定webclient已经下载了所有数据/字符串

时间:2014-01-16 09:07:28

标签: c# xaml windows-phone-8

我正在使用Windows Phone应用程序并与RESTful API(JSON)进行交互。我想要实现的是当我开始加载所有数据时它将显示一个进度指示器,并且在所有数据完成加载后(这意味着所有数据将在我的ListBox中可用),进度指示器将消失。

这是我正在使用的代码,但它似乎不起作用:

try
{
   isBusy = true;
   isBusyMessage = "Loading...";
   WebClient client = new WebClient();
   Uri uri = new Uri(transportURL1 + latitude + "%2C" + longitude + transportURL2, UriKind.Absolute);
   client.DownloadStringCompleted += (s, e) =>
   {
     if (e.Error == null)
     {
       RootObject result = JsonConvert.DeserializeObject<RootObject>(e.Result);
       hereRestProperty = new ObservableCollection<Item>(result.results.items);
     }
     else
     {
       MessageBox.Show(e.Error.ToString());
     }
   };
   client.DownloadStringAsync(uri);

   isBusy = false;
   isBusyMessage = "Finished";
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message);
}

isBusy与我的进度指示器绑定。

2 个答案:

答案 0 :(得分:0)

移动isBusy = false;到DownloadStringCompleted处理程序,在下载完成后更改isBusy:

isBusy = true;
isBusyMessage = "Loading...";
    WebClient client = new WebClient();
    Uri uri = new Uri(transportURL1 + latitude + "%2C" + longitude + transportURL2, UriKind.Absolute);
    client.DownloadStringCompleted += (s, e) =>
    {
        if (e.Error == null)
        {
            RootObject result = JsonConvert.DeserializeObject<RootObject>(e.Result);
            hereRestProperty = new ObservableCollection<Item>(result.results.items);
        }
        else
        {
            MessageBox.Show(e.Error.ToString());
        }
        // Dispatcher.Invoke for lines below, if needed
        // Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() => {
        isBusy = false;
        isBusyMessage = "Finished";
        // }));
    };
    client.DownloadStringAsync(uri);

答案 1 :(得分:0)

我会尝试等待。不幸的是,WP缺少方法DownloadStringTaskAsync(),所以要做到这一点我会做一个方法:

private Task<string> GetString(Uri uri)
{
   TaskCompletionSource<string> taskComplete = new TaskCompletionSource<string>();
   WebClient client = new WebClient();
   client.DownloadStringCompleted += (s, e) =>
   {
     if (e.Error == null) taskComplete.SetResult(e.Result);
     else taskComplete.SetException(e.Error);
   };
   client.DownloadStringAsync(uri);
   return taskComplete.Task;
}

private async Task myTask()            
{
  isBusy = true;
  isBusyMessage = "Loading...";
  Uri uri = new Uri(transportURL1 + latitude + "%2C" + longitude + transportURL2, UriKind.Absolute);
  string resultDownload = await GetString(uri);
  try
  {
    RootObject result = JsonConvert.DeserializeObject<RootObject>(resultDownload);
    hereRestProperty = new ObservableCollection<Item>(results.items);
  }
  catch (Exception err)                 
  {
    MessageBox.Show(err.Message);
  }
  isBusy = false;
  isBusyMessage = "Finished";
}

这只是另一种方式 - 对我来说这样做更简单。在这种情况下,您有一个异步任务,您可以等待或不等。