WebClient - wait until file has downloaded

后端 未结 2 1534
醉梦人生
醉梦人生 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: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 list = new List();
    
      GetData(data =>
      {
        foreach (var item in data)
        {
          list.Add(item);
          Console.WriteLine(item);
        }
        Console.WriteLine("Done");
      });
      Console.ReadLine();
    }
    
    public static void GetData(Action> callback)
    {
      WebClient webClient = new WebClient();
      webClient.DownloadStringCompleted += (s, e) =>
        {
          List data = new List();
          for (int i = 0; i < 5; i++)
          {
            data.Add(e.Result);
          }
          callback(e.Error == null ? data : Enumerable.Empty());
        };
    
      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 list = new List();
      list = await GetDataAsync();
    
      foreach (var item in list)
      {
        Console.WriteLine(item);
      }
    }
    
    public static async Task> GetDataAsync()
    {
      WebClient webClient = new WebClient();
      string result = await webClient.DownloadStringTaskAsync(new Uri("http://www.google.com"));
    
      List data = new List();
      for (int i = 0; i < 5; i++)
      {
        data.Add(result);
      }
      return data;
    }
    

提交回复
热议问题