本文介绍了如何找出这些网站中哪些失败了的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个异步任务,该任务要去几个网站解析一些数据,并在完成后返回数据.如果一个或多个网站失败-我需要找出哪些网站失败了.这可能吗?这是我的一些示例代码:

I have an asyncronous task that goes out to several websites parses some data and returns the data when its finished. In the event that one or more of the websites fail - I need to find out which ones failed. Is this possible? Here is some example code I have:

控制器

public async Task<ActionResult> Index()
{
    Models.WebSite ws = new Models.WebSite();
    List<Task<string>> webList = new List<Task<string>>();
    webList.Add(ws.GetWebsiteInfoAsync("http://website1.com"));
    webList.Add(ws.GetWebsiteInfoAsync("http://website2.com"));
    webList.Add(ws.GetWebsiteInfoAsync("http://website3.com"));

    var taskComplete = await Task.WhenAll(webList);
    return View(taskComplete);
}

发出网络请求的类:

public async Task<string> GetWebsiteInfoAsync(string url)
{
    System.Net.WebClient wc = new System.Net.WebClient();
    string result = null;
    result = await wc.DownloadStringTaskAsync(new Uri(url));
    return result;
}

推荐答案

您可以检查单个任务(当前存储在列表中).检查它们的属性,例如 Status IsFaulted .

You can examine the individual tasks (that you are storing in a list at the moment). Examine their properties, such as Status or IsFaulted.

taskComplete 完成后,所有单个网站任务也将完成.因此, await taskComplete ,吞下所产生的异常并检查网站任务.

As soon as taskComplete has completed, all individual website tasks will have completed as well. So await taskComplete, swallow the resulting exception and examine the website tasks.

这篇关于如何找出这些网站中哪些失败了的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 06:19