C# 如何在这种情况下使用 WebClient.DownloadDataAsync() 方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1585985/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 19:05:10  来源:igfitidea点击:

How to use the WebClient.DownloadDataAsync() method in this context?

c#asynchronousdownloadscreen-scraping

提问by Sergio Tapia

My plan is to have a user write down a movie title in my program and my program will pull the appropiate information asynchronously so the UI doesn't freeze up.

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

Here's the code:

这是代码:

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;
        }

My actual problem lies in the WebClientX.DownloadDataAsync() method. I can't use a string URL for it. How can I use that built in function to download the bytes of the site (for later use I will convert this to string, I know how to do this) and without freezing up my GUI?

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

Perhaps a clear cut example of the DownloadDataAsync so I can learn how to use it?

也许是 DownloadDataAsync 的一个清晰示例,以便我可以学习如何使用它?

Thanks SO, you're always such a great resource.

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

回答by Marc Gravell

You need to handle the DownloadDataCompletedevent:

您需要处理该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");
}

The args contains other bits of information relating to error conditions etc - check those too.

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

Also note that you'll be coming into DownloadDataCompletedon a different thread; if you are in a UI (winform, wpf, etc) you'll need to get to the UI thread before updating the UI. From winforms, use this.Invoke. For WPF, look at the Dispatcher.

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

回答by Rubens Farias

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);
}

回答by ssmsnet

If anyone using above in web application or websites please set Async = "true" in the page directive declaration in aspx file.

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

回答by Bill Forney

There is a newer DownloadDataTaskAsync method that allows you to await the result. It is simpler to read and easier to wire up by far. I'd use that...

有一个较新的 DownloadDataTaskAsync 方法可以让您等待结果。到目前为止,它更易于阅读且更易于连接。我会用那个...

var client = new WebClient();

var data = await client.DownloadDataTaskAsync(new Uri(imageUrl));

await outstream.WriteAsync(data, 0, data.Length);

回答by Hung Le

//using ManualResetEvent class

//使用 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);
}

回答by OnicDr

ThreadPool.QueueUserWorkItem(state => WebClientX.DownloadDataAsync(sitesearchURL));

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

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