Tasks

1. Why do we need tasks?

2. What is TaskCreationOptions?

There is no built-in way to get result of an asynchronous operation and there is no way to know whether an operation has completed. To solve this problem MS introduced the concepts of Tasks.

Sample 1:

        static void Main(string[] args)

        {

            CancellationTokenSource cts = new CancellationTokenSource();

            Task<int> task = new Task<int>(n => DoSomeWork((int)n), 10, cts.Token, TaskCreationOptions.None);           

            task.Start();

            //cts.Cancel();

            try

            {

                Console.WriteLine(task.Result);

            }

            catch (AggregateException ex)

            {

                foreach (var item in ex.InnerExceptions)

                {

                    Console.WriteLine(ex.ToString());

                }

            }

            Console.ReadKey();

        }

        private static int DoSomeWork(int n)

        {

            int sum = 1;

            checked

            {

                for (int i = 0; i < n; i++)

                {

                    sum += sum;

                }

            }

            return sum;

        }

We can specify type of the running task using a special parameter of the TaskCreationOptions  type.

 
 [SerializableAttribute]
  [FlagsAttribute]
  public enum TaskCreationOptions

 

Member Description
None Specifies that the default behavior should be used.
PreferFairness A hint to a TaskScheduler to schedule a task in as fair a manner as possible, meaning that tasks scheduled sooner will be more likely to be run sooner, and tasks scheduled later will be more likely to be run later.
LongRunning Specifies that a task will be a long-running, course-grained operation. It provides a hint to the TaskScheduler that oversubscription may be warranted.
AttachedToParent Specifies that a task is attached to a parent in the task hierarchy.