0

我将如何打印所有任务的结果,即使是那些没有运行完成的任务?例如,如果我收到内部伺服器错误或 404 未找到错误,我仍然想打印所有结果,包括运行完成的结果。

这是我的代码:

public List<Task> tasksList = new List<Task>(); // List of tasks being created
public IList<WebsiteResult> WebResult = new List<WebsiteResult>(); // List that holds the web results

private void CheckNewResult()
{
    Task.Factory.ContinueWhenAll(tasksList.ToArray(), CompleteTasks);
}

//Only runs if all tasks Ran to Completion
private void CompleteTasks(Task[] tasks){
    if(tasks.All(t => t.Status == TaskStatus.RanToCompletion))
    {
        for(var numResults = 0; numResults < WebResult.Count; numResults++)
        {
            Print Results(numResults); //print each url result in the list
        }
    }
}


/// Method to send to request and get the response
public void PageCheck(Website webParam, int mySiteCounter)
{
    HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(uri)
    // omit some code
    try 
    {
        Task<WebResponse> task = Task<WebResponse>.Factory.FromAsync(
        myReq.BeginGetResponse,
        myReq.EndGetResponse,
        null); 

        tasksList.Add(task);

        task.ContinueWith( t =>
        {
        // fill in web result list with the results using t.Result
        });
    }
    //catch omitted
}

public void PrintResults(int index){
// Print the results using info within web result list
}
4

1 回答 1

0

您可以在这些行中继续执行某些操作...注意带有泛型的任务。在我的例子中,我使用字符串来表示一条消息“Success!”,用作结果。这可以是您库中的任何自定义类。

public List<Task<string>> tasksList = new List<Task<string>>(); // List of tasks being created
    public IList<WebsiteResult> WebResult = new List<WebsiteResult>(); // List that holds the web results

    private void CheckNewResult()
    {
        Task.Factory.ContinueWhenAll(tasksList.ToArray(), CompleteTasks);
    }

    //Only runs if all tasks Ran to Completion
    private void CompleteTasks(Task<string>[] tasks)
    {
        tasks.Where(x => x.Status == TaskStatus.RanToCompletion).ForEach(x => {
            Console.WriteLine(x.Result);
        }); 
    } 
于 2013-07-16T13:06:17.757 回答