How to find out which of these sites failed

I have an asynchronous task that goes to several sites, parses some data, and returns data when completed. If one or more websites crashes, I need to find out which of them failed. Is it possible? Here is an example of the code that I have:

Controller

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

Class that makes web requests:

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;
}
+4
source share
2 answers

You can check individual tasks (which you now save in the list). Examine their properties, such as Statusor IsFaulted.

taskComplete , . , await taskComplete, -.

+3

/, URL- , Async.

, , .

, :

public class URLRequest
{
    public URLRequest(string url)
    {
        Url = url;
    }
    public string Url{get;set;}
    public string Result { get; set; }
}

:

        var requests = new List<URLRequest>();
        requests.Add(new URLRequest("http://website1.com"));
        requests.Add(new URLRequest("http://website2.com"));
        requests.Add(new URLRequest("http://website3.com"));

        foreach (var request in requests) {
          webList.Add(ws.GetWebsiteInfoAsync(request));
        }

URL- :

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

, :

        var message = new StringBuilder(500);
        foreach (var request in requests) {
          if (!string.IsNullOrEmpty(request.Result)) {
            if (message.Length == 0) {
                message.Append("Sorry, the following website(s) failed: ");
            } else {
                message.Append(", ");
            }
            message.Append(request.Url);
          }
        }

, ; , .

+1

All Articles