1

我有一个 C# 程序,它当前从多个站点同步下载数据,之后代码对我下载的数据进行了一些处理。我正在尝试移动它以异步进行下载,然后处理我下载的数据。我在这个排序上遇到了一些问题。下面是我正在使用的代码快照:

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Started URL downloader");
        UrlDownloader d = new UrlDownloader();
        d.Process();
        Console.WriteLine("Finished URL downloader");

        Console.ReadLine();
    }
}

class UrlDownloader
{
    public void Process()
    {
        List<string> urls = new List<string>() { 
            "http://www.stackoverflow.com", 
            "http://www.microsoft.com", 
            "http://www.apple.com", 
            "http://www.google.com" 
        };

        foreach (var url in urls)
        {
            WebClient Wc = new WebClient();
            Wc.OpenReadCompleted += new OpenReadCompletedEventHandler(DownloadDataAsync);
            Uri varUri = new Uri(url);
            Wc.OpenReadAsync(varUri, url);
        }
    }

    void DownloadDataAsync(object sender, OpenReadCompletedEventArgs e)
    {
        StreamReader k = new StreamReader(e.Result);
        string temp = k.ReadToEnd();
        PrintWebsiteTitle(temp, e.UserState as string);
    }

    void PrintWebsiteTitle(string temp, string source)
    {
        Regex reg = new Regex(@"<title[^>]*>(.*)</title[^>]*>");
        string title = reg.Match(temp).Groups[1].Value;

        Console.WriteLine(new string('*', 10));
        Console.WriteLine("Source: {0}, Title: {1}", source, title);
        Console.WriteLine(new string('*', 10));
    }
}

本质上,我的问题是这个。我上面的输出是:

Started URL downloader
Finished URL downloader
"Results of d.Process()"

我想要做的是完成 d.Process() 方法,然后返回到我的 Program 类中的“Main”方法。所以,我正在寻找的输出是:

Started URL downloader
"Results of d.Process()"
Finished URL downloader

我的 d.Process() 方法异步运行,但我不知道如何等待我的所有处理完成,然后再返回我的 Main 方法。关于如何在 C#4.0 中执行此操作的任何想法?我不确定如何“告诉”我的 Process() 方法等到所有异步活动完成后再返回 Main 方法。

4

2 回答 2

8

If you are on .NET>=4.0 you can use TPL

Parallel.ForEach(urls, url =>
{
    WebClient Wc = new WebClient();
    string page = Wc.DownloadString(url);
    PrintWebsiteTitle(page);
 });

I would also use HtmlAgilityPack to parse the page instead of regex.

void PrintWebsiteTitle(string page)
{
    HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
    doc.LoadHtml(page);
    Console.WriteLine(doc.DocumentNode.Descendants("title").First().InnerText);
}
于 2012-07-13T17:15:08.730 回答
0

我建议使用WebClient.DownloadDataAsync而不是自己编写。然后,您可以使用 Task Parallel Library 将对 DownloadDataAsync 的调用包装在 TaskCompletionSource 中,以获取可以等待或继续的多个 Task 对象:

        webClient.DownloadDataAsync(myUri);
        webClient.DownloadDataCompleted += (s, e) =>
                                           {
                                            tcs.TrySetResult(e.Result);
                                           };

        if (wait)
        {
            tcs.Task.Wait();
            Console.WriteLine("got {0} bytes", tcs.Task.Result.Length);
        }
        else
        {
            tcs.Task.ContinueWith(t => Console.WriteLine("got {0} bytes", t.Result.Length));
        }

要处理错误情况,可以扩展 TaskCompletionSource 的使用:

webClient.DownloadDataCompleted += (s, e) =>
                                {
                           if(e.Error != null) tcs.SetException(e.Error);
                           else if(e.Cancelled) tcs.SetCanceled();
                           else tcs.TrySetResult(e.Result);
                                 };

对多个任务执行类似操作:

Task.WaitAll(tcs.Task, tcs2.Task);

或者

Task.Factory.ContinueWhenAll(new Task[] {tcs.Task, tcs2.Task}, ts =>
                                                    {
                                                        /* do something with all the results */
                                                    });
于 2012-07-13T17:31:14.640 回答