如何打印所有任务结果?

时间:2013-07-16 12:55:39

标签: c# asynchronous task-parallel-library task

如果那些没有完成任务的那些任务的打印结果如何? 例如,如果我收到内部伺服器错误或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
}

1 个答案:

答案 0 :(得分:0)

您可以在这些行中继续...注意使用泛型的任务。在我的情况下,我使用字符串来表示可能是一个消息“成功!”,用作结果。这可以是您图书馆中的任何自定义类。

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