public static async Task AccessTheWebAsync(CancellationToken ct) { HttpClient client = new HttpClient(); // Make a list of web addresses. List <string> urlList = SetUpURLList(); // ***Create a query that, when executed, returns a collection of tasks. IEnumerable <Task <RoleSkills> > downloadTasksQuery = from url in urlList select ProcessURL(url, client, ct); // ***Use ToList to execute the query and start the tasks. List <Task <RoleSkills> > downloadTasks = downloadTasksQuery.ToList(); // ***Add a loop to process the tasks one at a time until none remain. while (downloadTasks.Count > 0) { // Identify the first task that completes. Task <RoleSkills> firstFinishedTask = await Task.WhenAny(downloadTasks); // ***Remove the selected task from the list so that you don't // process it more than once. downloadTasks.Remove(firstFinishedTask); // Await the completed task. RoleSkills content = await firstFinishedTask; Console.WriteLine("Role: {0}", content.Role); Console.WriteLine("Skills: {0}\n\n", String.Join(",", content.Skills)); } }
private static async Task <RoleSkills> ProcessURL(string url, HttpClient client, CancellationToken ct) { // GetAsync returns a Task<HttpResponseMessage>. HttpResponseMessage response = await client.GetAsync(url, ct); // Retrieve the website contents from the HttpResponseMessage. RoleSkills roleSkills = await response.Content.ReadAsAsync <RoleSkills>(); return(roleSkills); }