Ser*_*pia 17 c# asynchronous screen-scraping download
我的计划是让用户在我的程序中写下电影标题,我的程序将异步提取适当的信息,这样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;
}
Run Code Online (Sandbox Code Playgroud)
我的实际问题在于WebClientX.DownloadDataAsync()方法.我不能使用字符串URL.我如何使用内置函数来下载站点的字节(以后使用我将它转换为字符串,我知道如何做到这一点)并且不冻结我的GUI?
也许是DownloadDataAsync的明确示例,以便我可以学习如何使用它?
谢谢你,你总是这么好的资源.
Mar*_*ell 29
你需要处理这个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");
}
Run Code Online (Sandbox Code Playgroud)
args包含与错误条件等相关的其他信息 - 请检查这些信息.
另请注意,您将进入DownloadDataCompleted另一个线程; 如果您在UI(winform,wpf等)中,则需要在更新UI之前进入UI线程.从winforms,使用this.Invoke.对于WPF,请查看Dispatcher.
Bil*_*ney 29
有一个较新的DownloadDataTaskAsync方法,允许您等待结果.阅读起来更简单,更容易接线.我会用那个......
var client = new WebClient();
var data = await client.DownloadDataTaskAsync(new Uri(imageUrl));
await outstream.WriteAsync(data, 0, data.Length);
Run Code Online (Sandbox Code Playgroud)
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);
}
Run Code Online (Sandbox Code Playgroud)