static void Main() { WebDataDownloader downloader = new WebDataDownloader(); string[] addresses = { "http://www.msnbc.com", "http://www.yahoo.com", "http://www.nytimes.com", "http://www.washingtonpost.com", "http://www.latimes.com", "http://www.newsday.com" }; CancellationTokenSource cts = new CancellationTokenSource(); // Create a UI thread from which to cancel the entire operation Task.Factory.StartNew(() => { Console.WriteLine("Press c to cancel"); if (Console.ReadKey().KeyChar == 'c') cts.Cancel(); }); // Using a neutral search term that is sure to get some hits. Task<string[]> webTask = downloader.GetWordCounts(addresses, "the", cts.Token); // Do some other work here unless the method has already completed. if (!webTask.IsCompleted) { // Simulate some work. Thread.SpinWait(5000000); } string[] results = null; try { results = webTask.Result; } catch (AggregateException e) { foreach (var ex in e.InnerExceptions) { OperationCanceledException oce = ex as OperationCanceledException; if (oce != null) { if (oce.CancellationToken == cts.Token) { Console.WriteLine("Operation canceled by user."); } } else Console.WriteLine(ex.Message); } } if (results != null) { foreach (var item in results) Console.WriteLine(item); } Console.ReadKey(); }
private static void DowloadTest() { WebDataDownloader downloader = new WebDataDownloader(); string[] addresses = { "http://www.msnbc.com", "http://www.yahoo.com", "http://www.nytimes.com", "http://www.washingtonpost.com", "http://www.latimes.com", "http://www.newsday.com" }; CancellationTokenSource cts = new CancellationTokenSource(); string keyword = "the"; // Create a UI thread from which to cancel the entire operation Task.Factory.StartNew(() => { Console.WriteLine("Press c to cancel"); while (true) { if (Console.ReadLine().ToString().Equals("c", StringComparison.InvariantCultureIgnoreCase)) { cts.Cancel(); System.Environment.Exit(0); } else { keyword = Console.ReadLine(); } } }); // Using a neutral search term that is sure to get some hits. Task <string[]> webTask = downloader.GetWordCounts(addresses, keyword, cts.Token); // Do some other work here unless the method has already completed. //if (!webTask.IsCompleted) //{ // // Simulate some work. // Thread.SpinWait(5000000); //} string[] results = null; try { results = webTask.Result; } catch (AggregateException e) { foreach (var ex in e.InnerExceptions) { OperationCanceledException oce = ex as OperationCanceledException; if (oce != null) { if (oce.CancellationToken == cts.Token) { Console.WriteLine("Operation canceled by user."); } } else { Console.WriteLine(ex.Message); } } } if (results != null) { foreach (var item in results) { Console.WriteLine(item); } } Console.ReadKey(); }