staticvoidMain(string[] args) { // define the function Func<string> taskBody = new Func<string>(() => { Console.WriteLine("Task body working..."); return"Task Result"; });
// create the lazy variable Lazy<Task<string>> lazyData = new Lazy<Task<string>>(() => Task<string>.Factory.StartNew(taskBody));
Console.WriteLine("Calling lazy variable"); Console.WriteLine("Result from task: {0}", lazyData.Value.Result);
// do the same thing in a single statement Lazy<Task<string>> lazyData2 = new Lazy<Task<string>>( () => Task<string>.Factory.StartNew(() => { Console.WriteLine("Task body working..."); return"Task Result"; }));
Console.WriteLine("Calling second lazy variable"); Console.WriteLine("Result from task: {0}", lazyData2.Value.Result);
// wait for input before exiting Console.WriteLine("Main method complete. Press enter to finish."); Console.ReadLine(); }
// create the tasks Task task1 = new Task(() => { ArgumentOutOfRangeException exception = new ArgumentOutOfRangeException(); exception.Source = "task1"; throw exception; }); Task task2 = new Task(() => { thrownew NullReferenceException(); }); Task task3 = new Task(() => { Console.WriteLine("Hello from Task 3"); }); // start the tasks task1.Start(); task2.Start(); task3.Start(); // wait for all of the tasks to complete // and wrap the method in a try...catch block try { Task.WaitAll(task1, task2, task3); } catch (AggregateException ex) { // enumerate the exceptions that have been aggregated foreach (Exception inner in ex.InnerExceptions) { Console.WriteLine("Exception type {0} from {1}", inner.GetType(), inner.Source); } } // wait for input before exiting Console.WriteLine("Main method complete. Press enter to finish."); Console.ReadLine();
// create the cancellation token source and the token CancellationTokenSource tokenSource = new CancellationTokenSource(); CancellationToken token = tokenSource.Token; // create a task that waits on the cancellation token Task task1 = new Task(() => { // wait forever or until the token is cancelled token.WaitHandle.WaitOne(-1); // throw an exception to acknowledge the cancellation thrownew OperationCanceledException(token); }, token); // create a task that throws an exception Task task2 = new Task(() => { thrownew NullReferenceException(); }); // start the tasks task1.Start(); task2.Start(); // cancel the token tokenSource.Cancel(); // wait on the tasks and catch any exceptions try { Task.WaitAll(task1, task2); } catch (AggregateException ex) { // iterate through the inner exceptions using // the handle method ex.Handle((inner) => { if (inner is OperationCanceledException) { // ...handle task cancellation... returntrue; } else { // this is an exception we don't know how // to handle, so return false returnfalse; } }); } // wait for input before exiting Console.WriteLine("Main method complete. Press enter to finish."); Console.ReadKey();
privatestaticvoidMain(string[] args) { // create the task Task<int> task1 = new Task<int>(() => { int sum = 0; for (int i = 0; i < 100; i++) { sum += i; } return sum; });
task1.Start(); // write out the result Console.WriteLine("Result 1: {0}", task1.Result);
// create the task Task<int> task2 = Task.Factory.StartNew<int>(() => { int sum = 0; for (int i = 0; i < 100; i++) { sum += i; } return sum; });
// write out the result Console.WriteLine("Result 1: {0}", task2.Result);
staticvoidMain(string[] args) { // create the cancellation token source CancellationTokenSource tokenSource = new CancellationTokenSource();
// create the cancellation token CancellationToken token = tokenSource.Token; // create the task
Task task = new Task(() => { for (int i = 0; i < int.MaxValue; i++) { if (token.IsCancellationRequested) { Console.WriteLine("Task cancel detected"); thrownew OperationCanceledException(token); } else { Console.WriteLine("Int value {0}", i); } } }, token);
// wait for input before we start the task Console.WriteLine("Press enter to start task"); Console.WriteLine("Press enter again to cancel task"); Console.ReadLine();
// start the task task.Start();
// read a line from the console. Console.ReadLine();
// cancel the task Console.WriteLine("Cancelling task"); tokenSource.Cancel();
// wait for input before exiting Console.WriteLine("Main method complete. Press enter to finish."); Console.ReadLine(); }
// wait for input before we start the task Console.WriteLine("Press enter to start task"); Console.WriteLine("Press enter again to cancel task"); Console.ReadLine();
// start the task task.Start(); // read a line from the console. Console.ReadLine();
// cancel the task Console.WriteLine("Cancelling task"); tokenSource.Cancel();
// wait for input before exiting Console.WriteLine("Main method complete. Press enter to finish."); Console.ReadLine(); }
// create the cancellation token source CancellationTokenSource tokenSource = new CancellationTokenSource();
// create the cancellation token CancellationToken token = tokenSource.Token;
// create the task Task task1 = new Task(() => { for (int i = 0; i < int.MaxValue; i++) { if (token.IsCancellationRequested) { Console.WriteLine("Task cancel detected"); thrownew OperationCanceledException(token); } else { Console.WriteLine("Int value {0}", i); } } }, token);
// create a second task that will use the wait handle Task task2 = new Task(() => { // wait on the handle token.WaitHandle.WaitOne(); // write out a message Console.WriteLine(">>>>> Wait handle released"); });
// wait for input before we start the task Console.WriteLine("Press enter to start task"); Console.WriteLine("Press enter again to cancel task"); Console.ReadLine(); // start the tasks task1.Start(); task2.Start();
// read a line from the console. Console.ReadLine();
// cancel the task Console.WriteLine("Cancelling task"); tokenSource.Cancel();
// wait for input before exiting Console.WriteLine("Main method complete. Press enter to finish."); Console.ReadLine(); }
staticvoidMain(string[] args) { // create the cancellation token sources CancellationTokenSource tokenSource1 = new CancellationTokenSource(); CancellationTokenSource tokenSource2 = new CancellationTokenSource(); CancellationTokenSource tokenSource3 = new CancellationTokenSource();
// create a composite token source using multiple tokens CancellationTokenSource compositeSource = CancellationTokenSource.CreateLinkedTokenSource( tokenSource1.Token, tokenSource2.Token, tokenSource3.Token);
// create a cancellable task using the composite token Task task = new Task(() => { // wait until the token has been cancelled compositeSource.Token.WaitHandle.WaitOne(); // throw a cancellation exception thrownew OperationCanceledException(compositeSource.Token); }, compositeSource.Token);
// start the task task.Start();
// cancel one of the original tokens tokenSource2.Cancel();
// wait for input before exiting Console.WriteLine("Main method complete. Press enter to finish."); Console.ReadLine(); }
staticvoidMain(string[] args) { // create the cancellation token source CancellationTokenSource tokenSource = new CancellationTokenSource();
// create the cancellation token CancellationToken token = tokenSource.Token;
// create the first task, which we will let run fully Task task1 = new Task(() => { for (int i = 0; i < Int32.MaxValue; i++) { // put the task to sleep for 10 seconds bool cancelled = token.WaitHandle.WaitOne(10000); // print out a message Console.WriteLine("Task 1 - Int value {0}. Cancelled? {1}", i, cancelled); // check to see if we have been cancelled if (cancelled) { thrownew OperationCanceledException(token); } } }, token); // start task task1.Start();
// wait for input before exiting Console.WriteLine("Press enter to cancel token."); Console.ReadLine();
// cancel the token tokenSource.Cancel();
// wait for input before exiting Console.WriteLine("Main method complete. Press enter to finish."); Console.ReadLine(); }
staticvoidMain(string[] args) { // create the cancellation token source CancellationTokenSource tokenSource = new CancellationTokenSource();
// create the cancellation token CancellationToken token = tokenSource.Token;
// create the first task, which we will let run fully Task task1 = new Task(() => { for (int i = 0; i < Int32.MaxValue; i++) { // put the task to sleep for 10 seconds Thread.SpinWait(10000); // print out a message Console.WriteLine("Task 1 - Int value {0}", i); // check for task cancellation token.ThrowIfCancellationRequested(); } }, token);
// start task task1.Start();
// wait for input before exiting Console.WriteLine("Press enter to cancel token.");
Console.ReadLine(); // cancel the token tokenSource.Cancel();
// wait for input before exiting Console.WriteLine("Main method complete. Press enter to finish."); Console.ReadLine(); }