我有一个 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 方法。