如何在此上下文中使用WebClient.DownloadDataAsync()方法?我的计划是让用户在我的程序中写下电影标题,我的程序将异步提取适当的信息,这样UI就不会冻结。这是代码:publicclassIMDB{WebClientWebClientX=newWebClient();byte[]缓冲区=null;publicstring[]SearchForMovie(stringSearchParameter){//格式化搜索参数,使其形成有效的IMDB*SEARCH*url。//我们将从搜索网站中提取实际的电影//链接。字符串sitesearchURL=FindURL(SearchParameter);//有一个方法异步下载//IMDB*search*网站的整个源代码。Buffer=WebClientX.DownloadDataAsync(sitesearchURL);//将IMDB源代码传递给方法findInformation()。//string[]lol=findInformation();//????//Profit.string[]lol=null;返回大声笑;我的实际问题是WebClientX.DownloadDataAsync()方法。我不能使用字符串URL。我如何使用内置函数下载站点的字节(为了以后使用,我会将其转换为字符串,我知道该怎么做)而不冻结我的GUI?也许是DownloadDataAsync的一个清晰示例,以便我可以学习如何使用它?谢谢你,你总是这么好的资源。您需要处理DownloadDataCompleted事件:staticvoidMain(){stringurl="http://google.com";WebClient客户端=newWebClient();client.DownloadDataCompleted+=DownloadDataCompleted;client.DownloadDataAsync(newUri(url));控制台.ReadLine();}staticvoidDownloadDataCompleted(objectsender,DownloadDataCompletedEventArgse){byte[]raw=e.Result;Console.WriteLine(raw.Length+"接收到的字节数");}args包含与错误条件等相关的信息。有关其他信息,请查看这些信息。另请注意,您将在另一个线程上输入DownloadDataCompleted;如果您在UI(winform、wpf等)中,则需要在更新UI之前进入UI线程。在winforms中,使用this.Invoke。对于WPF,请查看Dispatcher。有一个更新的DownloadDataTaskAsync方法允许您等待结果。到目前为止,它更容易阅读,更容易连接。我会用那个...varclient=newWebClient();vardata=awaitclient.DownloadDataTaskAsync(newUri(imageUrl));等待outstream.WriteAsync(data,0,data.Length);如果在Web应用程序或网站中使用上述内容,请在aspx文件的页面指令声明中设置Async="true"。staticvoidMain(string[]args){byte[]data=null;WebClient客户端=newWebClient();client.DownloadDataCompleted+=delegate(objectsender,DownloadDataCompletedEventArgse){data=e.Result;};Console.WriteLine("开始...");client.DownloadDataAsync(新Uri(“http://stackoverflow.com/questions/”));while(client.IsBusy){Console.WriteLine("twaiting...");线程.睡眠(100);}Console.WriteLine("完成。接收到{0}个字节;",data.Length);}ThreadPool.QueueUserWorkItem(state=>WebClientX.DownloadDataAsync(sitesearchURL));http://工作博客。pilin.name/2009/02/system.html//使用ManualResetEvent类以上是C#学习教程:如何在这个上下文中使用WebClient.DownloadDataAsync()方法?所有分享的内容,如果对你有用,需要了解更多C#学习教程,希望大家多多关注—staticManualResetEventevnts=newManualResetEvent(false);staticvoidMain(string[]args){byte[]data=null;WebClient客户端=newWebClient();client.DownloadDataCompleted+=delegate(objectsender,DownloadDataCompletedEventArgse){data=e.结果;evnts.Set();};Console.WriteLine("开始...");evnts.Reset();client.DownloadDataAsync(新Uri(“http://stackoverflow.com/questions/”));evnts.WaitOne();//等待下载完成Console.WriteLine("done.{0}bytesreceived;",data.Length);}本文收集自网络,不代表立场。如涉及侵权,请点击右边联系管理员删除。如需转载请注明出处:
