. NET 4.0 Tasks (Task)

Source: Internet
Author: User
Tags visual studio 2010

With the advent of. NET 4.0, one notable difference between her and previous versions is the enhancement of parallel functionality to accommodate this multicore world. A new Concept---task is introduced as an important part of supporting parallel operation, as well as a complement and perfect to the thread pool. As we know, there are two obvious drawbacks to using the thread pool, which is that once we've put the task we're going to perform, when it's done, and we need to return the value after execution, we're not going to be able to get it in the built-in way. Because of the launch of the task, we made it easy to do parallel programming and did not care how the underlying is implemented, because it is more flexible than the thread pool, and if you can master the task, it is very helpful to write efficient parallel code.

First, the new task

under the System.Threading.Tasks namespace, there are two new classes, a task and its generic version task<tresult>, and these two classes are used to create the task, and if the code executed does not need to return a value, use the task, If you need to return a value, use task<tresult>.

There are two ways to create a task, one of which is to create a new task by using the Task.Factory.StartNew method, such as:

Task task = Task.Facotry.StartNew (() =>console.writeline ("Hello, world!")); /After this line of code executes, the task begins execution

Another approach is to create a new task through the constructor of the task class, such as:

Task task = new Task (() =>console.writeline ("Hello, world!")); /Here only the work to be done is given to the task, but the task does not begin

Task. Start ();//After the Start method is called, the task will start executing at some point in the future.

At the same time, we can call the wait method to wait for the task to complete or call the IsCompleted property to determine whether the task is complete. It is necessary to note that two methods of creating tasks can be combined with the TaskCreationOptions enumeration to achieve our specific control of the behavior of the task execution, and both of these creation methods allow us to pass a TaskCreationOptions object to cancel a running task , please see the cancellation of the task.

Ii. Cancellation of the Mission

the only constant in the world is change, and when external conditions change, we may cancel the task that is being performed. Prior to. NET 4.0. NET does not provide a built-in solution to cancel the code being executed in the thread pool, but in. NET 4.0, we have the cooperative cancellation mode, which makes it very easy to cancel the task that is being performed. As shown below:

Using System;       Using System.Threading; Using System.Threading.Tasks;

Namespace taskdemo      {           class program           {                static void Main ()                 {                    CancellationTokenSource cts = new CancellationTokenSource ();                    Task T = new Task (() = = Longruntask (cts. Token));                   T.start ();                    Thread.Sleep (;      )         & NBsp;   CTS. Cancel ();                    Console.read ();              }

        static void Longruntask (CancellationToken token)                {

            //The method here simulates a time-consuming work                    for (int i = 0; i < i++)  & nbsp;                 {                         if (!token. iscancellationrequested)                         {                            Thread.Sleep (; )                            Console.Write (".");                       }                        Else                         {                            Console.WriteLine ("Task cancellation");                             break;                       }                   }               }&Nbsp;         }      }

Iii. abnormal mechanism of the task

The unhandled exception that is generated during the execution of the task will temporarily hide it and load it into a collection. When we call the wait method or the result property, the task throws a AggregateException exception. We can get a Readonlycollection<exception> object by invoking the read-only property innerexceptions of the AggregateException object, which is the collection that stores the thrown exception. Its first element is the exception that was originally thrown. Similarly, the InnerException property of the AggregateException object returns the exception that was originally thrown.

It is worth noting that, due to the characteristics of the hidden mechanism of the task, once an exception is generated, if we do not invoke the corresponding method or property to view the exception, we cannot determine whether there is an exception (the task does not actively throw an exception). When a task object is reclaimed by GC, the Finalize method checks for an unhandled exception, and if it is unfortunate, then the Finalize method throws the AggregateException again, and if unfortunately we do not catch the exception, Our program will abort the operation immediately. What a catastrophe it would be if such a thing happened!

To avoid this unfortunate occurrence, we can handle this unhandled exception by registering the static Unobservedtaskexception event of the TaskScheduler class to avoid a program crash.

Iv. Task Initiation Tasks

One of the powerful and flexible tasks is that when we complete a task, we can automatically start the execution of a new task. As shown below:

Using system;      using system.threading;       using System.Threading.Tasks;

Namespace taskdemo      {           public Class autotask           {                static void Main ()                 {                    Task task = new Task (() = {Thread.Sleep (5000); Console.WriteLine ("Hello,"); Thread.Sleep (5000); });                   task. Start ();                   Task NewTask = task. ContinueWith (t = Console.WriteLine ("world!"));                    Console.read ();               }           }      }

For the ContinueWith method, we can match the Taskcontinuationoptions enumeration to get more of the behavior we want.

Five, sub-task

A task is to support a parent-child relationship by creating a new task in a task. As shown below:

Using System; Using System.Threading.Tasks;

Namespace taskdemo      {           class childtask           {                static void Main ()                 {                    Task parant = new Task (() =>                    {                        New Task (() = Console.WriteLine ("Hello")). Start ();                        New Task (() = Console.WriteLine (",")). Start ();                       New Task (() = Console.WriteLine ("World")). Start ();                        New Task (() = Console.WriteLine ("!")). Start ();                   });                   Parant. Start ();                   Console.ReadLine ();              }           }      }

It is important to note that the calls to the subtasks shown in the preceding code are not called in the order in which the code appears.

Vi. Mission Plant

In some cases, we will encounter the creation of a large number of tasks, and these tasks happen to share a state parameter (such as CancellationToken), in order to avoid a large number of calls to the task of the constructor and parameter passing again and again, We can use the task factory to handle this kind of mass creation work for us. As shown in the following code:

Using System;     Using System.Threading; Using System.Threading.Tasks;

Namespace taskdemo    {         public class factoryoftask          {             Static void Main ()              {                  Task parent = new Task (() =>                 {                      CancellationTokenSource cts = new CancellationTokenSource ();                      TaskFactory tf = new TaskFactory (CTS. Token);                      var childtask = new[]                      {                       TF. StartNew (() =>concretetask (CTS. Token)),                       TF. StartNew (() =>concretetask (CTS. Token)),                       TF. StartNew (() =>concretetask (CTS. Token))                      };

Thread.Sleep (5000);//This is the time when tasks such as sleep do not cancel the task CTS.                 Cancel (); }                 );

Parent.             Start ();//begin to perform task Console.read (); }

        static void Concretetask (CancellationToken token)             {                  while (true)                   {                      if (!token. iscancellationrequested)                       {                          Thread.Sleep ($);                          Console.Write (".");      &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&Nbsp;        }                      else                      {                          Console.WriteLine ("Mission cancellation");                          break;                     }                 }             }        }    }

Seven, Task scheduling program

Task Scheduler is implemented by the scheduler, currently,. NET 4.0 includes two task schedulers: the Thread pool Task Scheduler (thread Pool Task Scheduler) and the synchronization Context Task Scheduler (synchronization Scheduler). By default, applications use the thread pool Task Scheduler to call the thread pool's worker threads to complete tasks, such as asynchronous operations that are constrained by calculations. The synchronization Context Task Scheduler typically uses the UI thread to complete tasks related to Windows forms,windows Presentation Foundation (WPF) and Silverlight applications.

Fortunately,. NET 4.0 provides TaskScheduler abstract classes for developers to inherit to implement custom Task Scheduler development, interested students can try.

Viii. Summary

The task gives us more convenience and flexibility, and also brings more resource consumption than the thread pool. If you want to reduce resource consumption, it is better to use the thread pool QueueUserWorkItem method directly, and if you want more control and flexibility, the task is not the second choice. This needs our developers to weigh it out for themselves.

References: "CLR Via C #", Third edtion, Jeffrey richer,726 page-739 page

"Introducing. NET 4.0 with Visual Studio 2010", Alex mackey,106 page-111 page

Http://www.cnblogs.com/myshell/archive/2010/03/23/1692059.html

. NET 4.0 Tasks (Task)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.