WebClient - wait until file has downloaded

后端 未结 2 1518
醉梦人生
醉梦人生 2020-12-21 21:16

I\'m developing a function to return a collection, generated from an xml file.

Initially, I was using a local xml file for testing, but now I\'m ready to have the a

相关标签:
2条回答
  • 2020-12-21 21:18

    You move the foreach() loop to the completed event.

    And that indeed means you cannot return anything from the original method. Make it a void.

    This is how async I/O works, better get used to it. You will need to rethink your design.

    0 讨论(0)
  • 2020-12-21 21:31

    You should start to take a look at async programming. One (old school) way would be to implement a public event and subscribe to that event in the calling class.

    However, using callbacks is more elegant. I whipped up a simple (useless, but still conceptually valid) example that you can build upon:

    public static void Main(string[] args)
    {
      List<string> list = new List<string>();
    
      GetData(data =>
      {
        foreach (var item in data)
        {
          list.Add(item);
          Console.WriteLine(item);
        }
        Console.WriteLine("Done");
      });
      Console.ReadLine();
    }
    
    public static void GetData(Action<IEnumerable<string>> callback)
    {
      WebClient webClient = new WebClient();
      webClient.DownloadStringCompleted += (s, e) =>
        {
          List<string> data = new List<string>();
          for (int i = 0; i < 5; i++)
          {
            data.Add(e.Result);
          }
          callback(e.Error == null ? data : Enumerable.Empty<string>());
        };
    
      webClient.DownloadStringAsync(new Uri("http://www.google.com"));
    }
    

    If you want to jump onto the C# async bandwagon (link for WP7 implementation), you can implement it using the new async and await keywords:

    public static async void DoSomeThing()
    {
      List<string> list = new List<string>();
      list = await GetDataAsync();
    
      foreach (var item in list)
      {
        Console.WriteLine(item);
      }
    }
    
    public static async Task<List<string>> GetDataAsync()
    {
      WebClient webClient = new WebClient();
      string result = await webClient.DownloadStringTaskAsync(new Uri("http://www.google.com"));
    
      List<string> data = new List<string>();
      for (int i = 0; i < 5; i++)
      {
        data.Add(result);
      }
      return data;
    }
    
    0 讨论(0)
提交回复
热议问题