[Deep learning C #] task--Tasks

Source: Internet
Author: User

Brief introduction

. NET 4 contains the new namespace System.Threading.Tasks, which contains classes that abstract threading functionality. Use ThreadPool in the background. A task represents the work of a unit that should be completed. The work of this unit can be run in a separate thread, or it can start a task synchronously, which needs to wait for the thread to be activated. Using a task not only gives you an abstraction layer, but also gives you a lot of control over the underlying thread.
The task provides a lot of flexibility when arranging the work that needs to be done. For example, you can define continuous work-what to do after a task is completed. This can differentiate between the success of a task or not. In addition, you can schedule tasks in the hierarchy. For example, a parent task can create a new child task. This can create a dependency so that the parent task is canceled and its subtasks are canceled.

Start a task

To start a task, you can use the constructor and Start () method of the TaskFactory class or task class. The constructor of the task class provides greater flexibility in creating tasks.
When a task is started, an instance of the task class is created, with an action or action < object > delegate without parameters or with an object parameter, you can specify the code that should run, similar to the thread class. The following defines a method with no parameters. In the implementation code, write the D of the task to the console:
  

static void TaskMethod(){    Console.WriteLine("running in a task");    Console.WriteLine("Task id: {0}",Task.CurrentId);}

In the code above, you can see different ways to start a new task. The first method uses instantiating the TaskFactory class, where the Taskmedlod () method is passed to the StartNew () method, and the task is started immediately. The second method uses the constructor of the task class. When instantiating a task object, the task does not run immediately, but instead specifies the created state. It then calls the start () method of the task class to start the task. When using the task class, you can also call the runsynchronously () method In addition to the Start () method. The task is then started, but it is running in the caller's current thread, and the caller needs to wait until the end of the task. By default, tasks are run asynchronously.
  

    //using task factory    new TaskFactory();    Task t1 = tf.StartNew(TaskMethod);    //using the task factory via a task    Task t2 = Task.TaskFactory.StartNew(TaskMethod);    //using Task constructor    new Task(TaskMethod);    t3.Start();

When you use the constructor of the task class and the StartNew () method of the TaskFactory class, you can pass the value in the TaskCreationOptions enumeration. Set the longrunning option to notify the Task Scheduler that the task takes a long time to execute, so that the scheduler is more likely to use the new thread. If the task should be associated to a parent task and the parent task is canceled, the task should also be canceled, and the auachtoparent option should be set. A value of preferfairness indicates that the scheduler should extract the first task that is already waiting. If a task is created inside another task, this is not the default. If a task creates additional work using subtasks, the subtasks take precedence over other tasks. They do not end up in the queue of the online pool. If these tasks should be handled in a fair manner with all other tasks, set this option to preferfairness.
  

Task t4 = new Task(TaskMethod, TaskCreationOptions.PreferFairness);t4.Start();
Continuous tasks

By using a task, you can specify that after the task is complete, you should start running another specific task, such as a new task that uses the results of the previous task, which should perform some cleanup work if the previous task fails.
The task handler either takes no parameters or takes an object parameter, and the continuous handler has a parameter of the task type, where you can access information about the starting task:
  

static void Doonfirst () {Console. WriteLine("doing some task {0}", Task. CurrentID);Thread. Sleep( the);}static void Doonsecond (Task t) {Console. WriteLine("task {0} finished"T. Id);Console. WriteLine("This task ID {0}", Task. CurrentID);Console. WriteLine("Do some cleanup");Thread. Sleep( the);}

A continuous task is defined by invoking the ContinueWith () method on the task. You can also use the TaskFactory class to define. T1. The ContinueWith (Doonsecond) method indicates that a new task that calls the Doonsecond () method should start immediately at the end of the task T1. At the end of a task, you can start multiple tasks, and a continuous task can have another continuous task, as shown in the following example:

Task t1 = new Task(DoOnFirst);Task t2 = t1.ContinueWith(DoOnSecond);Task t3 = t1.ContinueWith(DoOnSecond);Task t4 = t2.ContinueWith(DoOnSecond);

  
Regardless of how the previous task ended, the preceding successive task always starts at the end of the previous task. Using the value in the Taskcontinuationoptions enumeration, you can specify that the continuous task starts only at the end of the start task (or failure). Some of the possible values are onlyonfaulted, notonfaulted, onlyoncanceled, notoncanceled, and Onlyonrantocompletion.
  

Task t5 = t1.ContinueWith(DoOnError, TaskContinuationOptions.OnlyOnFaulted);
Task hierarchy

With task continuity, you can start another task at the end of one task. Tasks can also form a hierarchy. When a task starts a new task, a parent/child hierarchy is started.
The following code snippet creates a new task inside the parent task. The code that creates the child task is the same as the code that creates the parent task, except that the task is created from within another task.
  

static void Parentandchild () {var parent = new Task (parenttask);Parent. Start();Thread. Sleep( -);Console. WriteLine(Parent. Status);Thread. Sleep(4000);Console. WriteLine(Parent. Status);}static void Parenttask () {Console. WriteLine("task ID {0}", Task. CurrentID);var child = new Task (childtask);Child. Start();Thread. Sleep( +);Console. WriteLine("Parent started child");}static void Childtask () {Console. WriteLine("Child");Thread. Sleep( the);Console. WriteLine("Child finished");}

If the parent task ends before the child task, the state of the parent task is displayed as Waitingforchildrentocomplete. As long as the subtasks end, the state of the parent task becomes rantocompletion. Of course, this is not valid if the parent task creates a subtask with Detachedfromparent in the TaskCreationOptions enumeration.

The result of the task

At the end of the task, it can write some useful state information to the shared object. This shared object must be thread-safe. Another option is to use a task that returns a result. Using the generic version of the task class, you can define the return type of the task that returns a result.
The method that is called to return a result task can be declared with any return type. Example Method Startwithresult () returns two int values using a tuple. The input to the method can be either void or object type, as follows:
  

static  Tuple<int , int  > Taskwithresult (Object Division) {Tuple <int , int  >     div  = (tuple<int , int  >) Division; int  result = div . Item1/div .    ITEM2; int  reminder = div . Item1%div .    ITEM2;    Console.WriteLine ( "task creates a result ..." ); return  Tuple.create<int , int  > (Result, reminder);}  

To define a task that calls the Startwithresult () method, use a generic class task < Tresult ; . The generic parameter defines the return type. This method is passed to the Func delegate through a constructor, and the second parameter defines the input value. Because this task requires two input values in the object parameter, a tuple is also created. The task is then started. The result property of the task instance T1 is disabled and waits until the task finishes. When the task finishes, the result property contains the results of the task.

var t1 = new Task<tuple<int, int>> (TaskWithResult, Tuple <int, int> (8 , 3 ))  T1 ()  Console (T1)  T1 ()  Console ( "result from task: {0} {1}" , T1  1, t1  2)   

Note: In the previous example, the Task < Tresult > constructor called the Taskfactory.startnew method (Func < Object, Tresult > , Object) overload.
function
Type: System.Func < Object, TResult >
A function delegate that returns future results that can be obtained through the task.

State
Type: System.Object
The object that contains the data used by the function delegate.

So we can see why we are creating a new tuple object when instantiating T1.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

[Deep learning C #] task--Tasks

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.