如何在此上下文中使用WebClient.DownloadDataAsync()方法?

我的计划是让用户在我的程序中写下电影标题,我的程序将异步提取适当的信息,这样UI就不会冻结。

这是代码:

public class IMDB { WebClient WebClientX = new WebClient(); byte[] Buffer = null; public string[] SearchForMovie(string SearchParameter) { //Format the search parameter so it forms a valid IMDB *SEARCH* url. //From within the search website we're going to pull the actual movie //link. string sitesearchURL = FindURL(SearchParameter); //Have a method download asynchronously the ENTIRE source code of the //IMDB *search* website. Buffer = WebClientX.DownloadDataAsync(sitesearchURL); //Pass the IMDB source code to method findInformation(). //string [] lol = findInformation(); //???? //Profit. string[] lol = null; return lol; } 

我的实际问题在于WebClientX.DownloadDataAsync()方法。 我不能使用字符串URL。 如何使用内置函数下载站点的字节(以后使用我会将其转换为字符串,我知道如何做到这一点)并且不冻结我的GUI?

也许是DownloadDataAsync的明确示例,以便我可以学习如何使用它?

谢谢你,你总是这么好的资源。

您需要处理DownloadDataCompleted事件:

 static void Main() { string url = "http://google.com"; WebClient client = new WebClient(); client.DownloadDataCompleted += DownloadDataCompleted; client.DownloadDataAsync(new Uri(url)); Console.ReadLine(); } static void DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e) { byte[] raw = e.Result; Console.WriteLine(raw.Length + " bytes received"); } 

args包含与错误条件等相关的其他信息 – 请检查这些信息。

另请注意,您将在另一个线程上进入DownloadDataCompleted ; 如果您在UI(winform,wpf等)中,则需要在更新UI之前进入UI线程。 从winforms,使用this.Invoke 。 对于WPF,请查看Dispatcher

有一个较新的DownloadDataTaskAsync方法,允许您等待结果。 它更容易阅读,更容易连接到目前为止。 我会用那个……

 var client = new WebClient(); var data = await client.DownloadDataTaskAsync(new Uri(imageUrl)); await outstream.WriteAsync(data, 0, data.Length); 

如果在Web应用程序或网站上使用上述任何人,请在aspx文件的页面指令声明中设置Async =“true”。

 static void Main(string[] args) { byte[] data = null; WebClient client = new WebClient(); client.DownloadDataCompleted += delegate(object sender, DownloadDataCompletedEventArgs e) { data = e.Result; }; Console.WriteLine("starting..."); client.DownloadDataAsync(new Uri("http://stackoverflow.com/questions/")); while (client.IsBusy) { Console.WriteLine("\twaiting..."); Thread.Sleep(100); } Console.WriteLine("done. {0} bytes received;", data.Length); } 
 ThreadPool.QueueUserWorkItem(state => WebClientX.DownloadDataAsync(sitesearchURL)); 

http://workblog.pilin.name/2009/02/system.html

//使用ManualResetEvent类

 static ManualResetEvent evnts = new ManualResetEvent(false); static void Main(string[] args) { byte[] data = null; WebClient client = new WebClient(); client.DownloadDataCompleted += delegate(object sender, DownloadDataCompletedEventArgs e) { data = e.Result; evnts.Set(); }; Console.WriteLine("starting..."); evnts.Reset(); client.DownloadDataAsync(new Uri("http://stackoverflow.com/questions/")); evnts.WaitOne(); // wait to download complete Console.WriteLine("done. {0} bytes received;", data.Length); }