Task Parallel Programming C #

1. Create a Task

There are two ways to create Task, one is a direct creation --new out, one is created through the factory.

        // create a first way, directly instantiated 
         var Task1 the Task new new = (() => 
         { 
            // you code the TODO 
         });
         task1.Start();

This is the easiest way to create, you can see its constructor is a Action.

        // Create a second embodiment, the factory creates 
         var Task.Factory.StartNew Task2 = (() => 
         { 
            // you code the TODO 
         });

In this way through the static factory, in order to create a Task and run.

By constructor creates a task, you must manually Start, and factory created directly by Task started.

 

2. Task brief life cycle (state):

The Created : indicates the default initialization tasks, but examples of "factory created" skip.

WaitingToRun : This state represents a thread waiting task scheduler allocates tasks to perform.

RanToCompletion : the task is finished.

 

3. Task mission control

Task most attractive place is his mission control, and you can be well controlled task execution order, so that multiple task and orderly work.

Task.Wait     is to wait for the completion of the task execution

Task.WaitAll     is to wait for the completion of all tasks executed

Task.WaitAny     is to wait for completion of any task continues downward

Task.ContinueWith     is to start next Task automatically after the first Task completed to achieve the continuation of Task

Task Cancellation   For example, we launched a task, abnormal or the user clicks Cancel, and so on, we have to cancel this task, then we have to cancel by tokens cancellation of a Task. In many Task of Body which contains a loop, we can judge whether the polling time IsCancellationRequested property is True, if it is True, then to return.

         var tokenSource = new CancellationTokenSource();
         var token = tokenSource.Token;
         var task = Task.Factory.StartNew(() =>
         {
            for (var i = 0; i < 1000; i++)
            {
               System.Threading.Thread.Sleep(1000);
               if (token.IsCancellationRequested)
               {
                  Console.WriteLine("Abort mission success!");
                  return;
               }
            }
         }, token);
         token.Register(() =>
         {
            Console.WriteLine("Canceled");
         });
         Console.WriteLine("Press enter to cancel task...");
         Console.ReadKey();
         tokenSource.Cancel();
         Console.ReadKey();

Here opens up a Task, and to register a token method, output a message, and then perform ReadKey start waiting for user input, the user clicks Enter, tokenSource.Cancel execution method, to cancel the task.

 

4. Task exception handling

     static void Main(string[] args)
      {
         try
         {
            var pTask = Task.Factory.StartNew(() =>
            {
               var cTask = Task.Factory.StartNew(() =>
               {
                  System.Threading.Thread.Sleep(2000);
                  throw new Exception("cTask Error!");
                  Console.WriteLine("Childen task finished!");
               });
               throw new Exception("pTask Error!");
               Console.WriteLine("Parent task finished!");
            });

            pTask.Wait();
         }
         catch (AggregateException ex)
         {
            foreach (Exception inner in ex.InnerExceptions)
            {
               Console.WriteLine(inner.Message);
            }
         }
         Console.WriteLine("Flag");
         Console.Read();
      }
 

Here with the AggregateException, is the abnormal collection, in order to capture the true exception information.

 

 

 

 

 

*****************************************************
*** No matter how far you go, looking back is also necessary. ***
*****************************************************

Guess you like

Origin www.cnblogs.com/gangle/p/11598364.html