public async Task TenK_WithNormalTimers() { List <Task> timers = new List <Task>(this.timeouts.Count); List <WorkerWithTimer> workers = new List <WorkerWithTimer>(this.timeouts.Count); for (int i = 0; i < this.timeouts.Count; i++) { WorkerWithTimer timer = new WorkerWithTimer(this.timeouts[i]); timers.Add(timer.StartTimerAsync()); } await Task.WhenAll(timers); foreach (WorkerWithTimer item in workers) { item.Dispose(); } }
static void Main() { WorkerWithTimer worker = new WorkerWithTimer(); CancellationTokenSource cts = new CancellationTokenSource(); // Task for UI thread, so we can call Task.Wait wait on the main thread. Task.Run(() => { Console.WriteLine("Press 'c' to cancel within 3 seconds after work begins."); Console.WriteLine("Or let the task time out by doing nothing."); if (Console.ReadKey(true).KeyChar == 'c') { cts.Cancel(); } }); // Let the user read the UI message. Thread.Sleep(1000); // Start the worker task. Task task = Task.Run(() => worker.DoWork(cts.Token), cts.Token); try { task.Wait(cts.Token); } catch (OperationCanceledException e) { if (e.CancellationToken == cts.Token) { Console.WriteLine("Canceled from UI thread throwing OCE."); } } catch (AggregateException ae) { Console.WriteLine("AggregateException caught: " + ae.InnerException); foreach (var inner in ae.InnerExceptions) { Console.WriteLine(inner.Message + inner.Source); } } Console.WriteLine("Press any key to exit."); Console.ReadKey(); cts.Dispose(); }
public async Task One_WithNormalTimers() { WorkerWithTimer timer = new WorkerWithTimer(50); await timer.StartTimerAsync(); }