Multi-thread tasks

Source: Internet
Author: User

the parallel task of the parallel class (http://www.cnblogs.com/afei-24/p/6904179.html) needs to end before it can run the following code, and if you want to start the action after the end, You can use the task class to better control parallel actions.
a task represents a unit of work that should be completed. This unit of work can be run in a separate thread, or it can start a task synchronously, which requires waiting for the thread. Using a task not only gives you an abstraction layer, but also gives you a lot of control over the underlying thread.
The task relative to the parallel class provides a lot of flexibility. For example, you can define continuous work-what to do after a task is completed. This can be divided according to the success of the task. You can also schedule tasks in the hierarchy. For example, a parent task can create a new child task.

I. 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 is more flexible in creating tasks.
When you start a task, you create an instance of the task class, using an action or action<t> delegate (without parameters or with a parameter), to specify the code that should run.

1. Tasks using the thread pool  
The thread pool provides a pool of background threads (the thread pool is described in detail later). The thread pool manages threads on its own, increasing or decreasing the number of threads in the thread pool as needed. Threads in the thread pool are used to implement some actions, and then still return to the thread pool.

Here are four ways to create a thread pool task:
first define a method to invoke using:

//avoid writing to the console for cross-over, where you use the Lock keyword to synchronize        Static ObjectTaskmethodlock =New Object(); Static voidTaskmethod (Objecttitle) {            Lock(Taskmethodlock) {Console.WriteLine (title); Console.WriteLine ("Task Id:{0},thread:{1}", Task.currentid,thread.currentthread.managedthreadid); Console.WriteLine ("is pooled thread:{0}", Thread.CurrentThread.IsThreadPoolThread); Console.WriteLine ("is background thread:{0}", Thread.CurrentThread.IsBackground); }        }

(1). Using the instantiated TaskFactory class, pass the parameters of the Taskmethod method and the Taskmethod method to the StartNew method:
var tf = new TaskFactory ();
Task t1 = tf. StartNew (Taskmethod, "Using a task Factory");

(2). Use the static property of the task class factory to access TaskFactory to invoke the StartNew () method. Similar to the first, the factory is used, but the control of the factory is not so comprehensive.
Task t2 = Task.Factory.StartNew (Taskmethod, "using Factory via a Task");

(3). Use the constructor of the task. When instantiating a task object, the task does not execute, but specifies the created state. Then call the start () method to start the task.
task t3 = new Task (Taskmethod, "using a Task constructor and Start");
T3. Start ();

(4). The run () method that calls the task class directly initiates the task. The Run () method does not pass a version with a parameter delegate, which can be passed by passing a lambda expression.
Task T4 = Task.run (() = Taskmethod ("Using Run method");

Static voidMain (string[] args) {            vartf =NewTaskFactory (); Task T1= TF. StartNew (Taskmethod,"using a task factory"); Task T2= Task.Factory.StartNew (Taskmethod,"using factory via a task"); Task T3=NewTask (Taskmethod,"using a task constructor and Start"); T3.            Start (); Task T4= Task.run (() = Taskmethod ("using Run method"));        Console.readkey (); }

  2. Synchronizing tasks
The task does not necessarily use threads in the thread pool, but it can also use other threads. Tasks can also run synchronously, using the same thread as the keynote thread.
Example:

  static  void   Runsynctask () {Taskmethod ( "  main thread  "   var  t = new  Task (taskmethod, " run sync  "                 

output:


The above code calls the Taskmethod method directly on the main thread and then on the created task. As seen from the output, the main thread is a foreground thread, no task ID, and no thread in the thread pool. When you call the RunSynchronously method, the same thread is used, and a task is created.

3. Tasks with separate threads
The task above is not a thread in the thread pool, but is using the main thread, not alone, and cannot be implemented asynchronously.
If the code of the task should run for a long time, You should use taskcreationoptions.longrunning to tell the Task Scheduler to create a new, separate thread instead of a thread in the thread pool. This thread can not be managed by the thread pool. When a thread is coming from the thread pool, the task scheduler can decide to wait for the task that is already running to complete, and then use that thread instead of creating a new thread in the threaded pool. For long-running threads, the Task Scheduler immediately knows that it is unwise to wait for them to complete and creates a new thread.

example:

  static  void   Longruntask () { var  t = new  Task (taskmethod,"  long Running   " ,                taskcreationoptions.longrunning);            T.start (); }

Output:
  


Two. The outcome of the task ———— future
At the end of the task, you 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. This kind of task is also called the future, because it returns a result. This requires the use of a generic version of the task class. Use this class to define the type of results returned by the task.
Example:
Using the generic class Task<tresult>,tresult is the return type. Through the constructor, the method is passed to the Func delegate, and the second parameter is the parameter of the delegate.

Static voidMain (string[] args) {                vart =Newtask<tuple<int,int>> (taskwithresult,tuple.create<int,int> (8,3));                T.start ();                Console.WriteLine (T.result);                T.wait (); Console.WriteLine ("result from task:{0},{1}", T.result.item1, t.result.item2);            Console.readkey (); }

A method that is called by a task to return a result can be declared as any type.

Statictuple<int,int> Taskwithresult (Objecto) {Tuple<int,int> div = (tuple<int,int>) O; intresult = Div. ITEM1/Div.            ITEM2; intReminder = Div. Item1%Div.            ITEM2; Thread.Sleep (10000); returntuple.create<int,int>(Result,reminder); }

Tuples (http://www.cnblogs.com/afei-24/p/6738155.html) are used here.

Three. Continuous tasks
By using a task, you can specify that another specific task should be run after the task completes. For example, a new task that uses the results of the previous task, and if the previous task fails, the task should perform some cleanup work.
The task handler (the previous task) 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 previous task.
Example:

//at the end of a task, you can start multiple tasks, and successive tasks can have another continuous task.         Static voidMain (string[] args) {Task T1=NewTask (Dofirst); Task T2=t1.            ContinueWith (Dosecond); Task T3=t1.            ContinueWith (Dosecond); Task T4=T2.            ContinueWith (Dosecond); T1.            Start ();        Console.readkey (); }        Static voidDofirst () {Console.WriteLine ("Do some task:{0}", Task.currentid); Thread.Sleep ( the); }        Static voidDosecond (Task t) {Console.WriteLine ("Task {0} finished", t.id); Console.WriteLine ("This task id:{0}", Task.currentid); }

No matter how the previous task ends, the preceding successive tasks are always started at the end of the previous task. Using the values in the Taskcontinuationoptions enumeration, you can specify that continuous tasks start only when the task succeeds or fails.
Task T5 = t1. ContinueWith (dosecond,taskcontinuationoptions.onlyonfaulted);


Four. Hierarchical structure of tasks
With task continuity, you can start another task at the end of one task. Tasks can also form a hierarchy. When a new task is started in a task, a parent/child hierarchy is started. Canceling the parent task also cancels the child task.
Creating a subtask is the same as the code that creates the parent task, except that the child task is created from within another task.
Example:

Static voidMain (string[] args) {Task T=NewTask (Parenttask);            T.start ();        Console.readkey (); }        Static voidParenttask () {Console.WriteLine ("Parent Task Id:{0}", Task.currentid); varChild =NewTask (Childtask); Child.            Start (); Console.WriteLine ("Parent Create Child"); }        Static voidChildtask () {Console.WriteLine ("Child Task"); }

If the parent task ends before the child task, the state of the parent task is waitingforchildrentocomplete. When all subtasks also end, the state of the parent task is rantocompletion.

Multi-thread 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.