我的应用程序从各种网址下载数据。每次URL下载完成时我都想知道 - 成功还是失败。为此,我有以下代码。
static void Main(string[] args)
{
var URLsToProcess = new List<string>
{
"http://www.microsoft.com",
"http://www.stackoverflow.com",
"http://www.google.com",
"http://www.apple.com",
"http://www.ebay.com",
"http://www.oracle.com",
"http://www.gmail.com",
"http://www.amazon.com",
"http://www.outlook.com",
"http://www.yahoo.com",
"http://www.amazon124.com",
"http://www.msn.com"
};
var tasks = URLsToProcess.Select(uri => DownloadStringAsTask(new Uri(uri))).ToArray();
while (tasks.Any())
{
try
{
//Task.WaitAll(tasks);
int index = Task.WaitAny(tasks);
Console.WriteLine("{0} has completed", tasks[index].AsyncState.ToString());
tasks = tasks.Where(t => t != tasks[index]).ToArray();
break;
}
catch (Exception e)
{
foreach (var t in tasks.Where(t => t.Status == TaskStatus.Faulted))
Console.WriteLine("{0} has failed", t.AsyncState.ToString());
// handle exception/report progress...
tasks = tasks.Where(t => t.Status != TaskStatus.Faulted).ToArray();
}
}
}
static Task<string> DownloadStringAsTask(Uri address)
{
TaskCompletionSource<string> tcs = new TaskCompletionSource<string>(address);
WebClient client = new WebClient();
client.DownloadStringCompleted += (sender, args) =>
{
if (args.Error != null)
tcs.SetException(args.Error);
else if (args.Cancelled)
tcs.SetCanceled();
else
tcs.SetResult(args.Result);
};
client.DownloadStringAsync(address);
return tcs.Task;
}
但是我只在输出中获得一个URL。知道我在这里做错了吗?
答案 0 :(得分:1)
您的break
循环中有一个无关的while
:
while (tasks.Any())
{
try
{
//Task.WaitAll(tasks);
int index = Task.WaitAny(tasks);
Console.WriteLine("{0} has completed", tasks[index].AsyncState.ToString());
tasks = tasks.Where(t => t != tasks[index]).ToArray();
//break; // NOTE: extraneous break that I have commented out
}
使用break
,,您的代码在我的机器上产生以下输出:
http://www.microsoft.com/ has completed
如上所示,break
已注释,您的代码在我的机器上产生了以下输出:
http://www.microsoft.com/ has completed
http://www.apple.com/ has completed
http://www.oracle.com/ has completed
http://www.amazon124.com/ has completed
http://www.google.com/ has completed
http://www.msn.com/ has completed
http://www.stackoverflow.com/ has completed
http://www.amazon.com/ has completed
http://www.ebay.com/ has completed
http://www.gmail.com/ has completed
http://www.outlook.com/ has completed
http://www.yahoo.com/ has completed