2010-05-08 69 views
2

我不确定为什么回调方法没有被全部触发。我使用VS 2010WebClient DownloadStringCompleted从未在控制台应用程序中被解雇

static void Main(string[] args) 
     { 
      try 
      { 
       var url = "some link to RSS FEED"; 
       var client = new WebClient(); 
       client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted); 
       client.DownloadDataCompleted += new DownloadDataCompletedEventHandler(client_DownloadDataCompleted); 

       client.DownloadStringAsync(new Uri(url)); 
      } 
      catch (Exception ex) 
      { 
       Console.WriteLine(ex.Message); 
      } 
     } 
     // THIS IS NEVER FIRED 
     static void client_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e) 
     { 
      Console.WriteLine("something"); 
     } 

     // THIS IS NEVER FIRED 
     static void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) 
     { 
      Console.WriteLine("do something"); 

      var rss = XElement.Parse(e.Result); 

      var pictures = from item in rss.Descendants("channel") 
          select new Picture 
          { 
           Name = item.Element("title").Value 
          }; 

      foreach (var picture in pictures) 
      { 
       Console.WriteLine(picture.Name); 
       Console.WriteLine(picture.Url); 
      } 

     } 
+0

你有没有得到答案? – 2011-04-21 13:42:33

回答

3

如果调用DownloadDataAsync()DownloadDataCompleted事件。如果您拨打DownloadStringAsync()方法,则会触发DownloadStringCompleted

为了让DownloadDataCompleted事件,火灾,请尝试:

static void Main(string[] args) 
     { 
      try 
      { 
       var url = "http://blog.gravitypad.com"; 
       //client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted); 
       client.DownloadDataCompleted += new DownloadDataCompletedEventHandler(client_DownloadDataCompleted); 

       client.DownloadDataAsync(new Uri(url)); 
       Console.ReadLine(); 
      } 
      catch (Exception ex) 
      { 
       Console.WriteLine(ex.Message); 
      } 
     } 
+0

应该提到:DownloadDataAsync将返回结果作为字节数组,其中DownloadStringAsync将以字符串形式返回结果。 – 2010-05-08 03:33:21

+0

我在上面的代码中调用DownloadStringAsync方法! – azamsharp 2010-05-08 03:37:45

+0

没错,但是您期待着DownloadDataCompleted事件触发。只有DownloadStringCompleted甚至会触发...除非你调用DownloadDataAsync。 – 2010-05-08 04:02:24

1

我有这个问题,并意识到URI是不正确的。我的意思是事件不会触发,除非文件被正确读取。所以我把我的xml文件放在ClientBin中,它的功能很神奇!

相关问题