Multithreading-task, Await/async

Source: Internet
Author: User
Tags instance method

Task Creation no return value

The task is a multi-threaded class that is netframwork3.0 re-installed. The reason for the previous multithreading (thread ThreadPool) is not good. (. NET framwork is also the development of the now EF, just beginning to be an edmx file, now the code FIRST,EF is lightweight.) But other technologies are dead.

Task has the characteristics of controllability, return value, simple code writing, good performance and so on thread execution.

There are three main ways of task creation

1. Task parameters

New Task (() ={    for (int0; i++ )    {        Console.WriteLine (i);    }}); T.start ();
View Code

Action,action<object>,object state,cancellationtoken,taskcreationoptions

Object: A parameter with a parameter delegate.

CancellationToken: Thread Cancellation notification

TaskCreationOptions: Controlling how tasks are executed

////Summary://flags that specify the optional behavior that controls the creation and execution of tasks. [Flags] Public enumtaskcreationoptions{//    //Summary://Specifies that the default behavior should be used. None =0,    //    //Summary://tip System.Threading.Tasks.TaskScheduler to schedule tasks in a way that is as fair as possible, which means that earlier scheduled tasks are more likely to run earlier, and tasks that are scheduled to run later are more likely to run later. Preferfairness =1,    //    //Summary://specifies that the task will be a long-running, coarse-grained operation involving fewer and larger components than the refinement system. It's going to System.Threading.Tasks.TaskScheduler//tip, oversubscription may be justified. You can create more threads than the number of available hardware threads by oversubscription. longrunning =2,    //    //Summary://specifies that a task is attached to a parent in the task hierarchy. For more information, see attached and detached subtasks. AttachedToParent =4,    //    //Summary://If you try to attach a subtask to the created task, the specified System.InvalidOperationException will be thrown. Denychildattach =8,    //    //Summary://prevents the environment scheduler from being considered as the current scheduler for the created task. This means that the execution of a task, such as StartNew or ContinueWith, will be considered System.Threading.Tasks.TaskScheduler.Default//The current scheduler. Hidescheduler = -}
View Code

2, Task.Factory.StartNew

Action,action<object>,object State,cancellationtoken,taskcreationoptions,taskscheduler

TaskScheduler: definition: The System.Threading.Tasks.TaskScheduler used to schedule the created System.Threading.Tasks.Task. (And don't see what it means, English meaning Task Scheduler)

The return value is a task

Task.Factory.StartNew (() ={    for (int; i++ )    {        Console.WriteLine (i);    }});
View Code

3, TaskFactory

Task.factory is an example of TaskFactory.

New={    for (int; i++ )    {        Console.WriteLine (i);    }});
View Code

All of the above are tasks with no return parameters

Task creates a return value

The return type in a generic project will encapsulate a generic type for a particular purpose. All will have a return value.

task<stringnew task<string>(GetName); T.start (); Console.WriteLine (T.result); Console.WriteLine (" end ");
View Code
 Public Static string GetName () {    for (int0; i++ )    {        Console.WriteLine ( i);    }     return " Shang " ;}
View Code

Note that when you get the return value, T.result is stuck on the thread, and one waits for the thread to return the result.

Task waits

1, why wait, because most of the thread to calculate has given the result, so we have to wait for this result.

2, public void Wait (..... );

is located in the task class (instance method. There are also several static methods).

Definition: Wait for the System.Threading.Tasks.Task to complete execution (other threads are stuck).

The parameter can set the wait time, and the task can be canceled during the CancellationToken (task cancel) wait.

3. public static void WaitAll (params task[] tasks ...);

Definition: Waits for all System.Threading.Tasks.Task objects provided to complete the execution process. (that is, the current thread waits for this parameter list to execute after all the threads have finished executing.) Note: WaitAll the other child threads in front of you still continue to execute)

Parameters: Waiting for Task List, events, CancellationToken

4, public static int WaitAny (params task[] tasks);

Definition: waits for any of the supplied System.Threading.Tasks.Task objects to complete the execution process.

Parameters: Waiting for Task List, events, CancellationToken

5. Attribute method of Task

AsyncState is when the task core method takes parameters, the value of the parameter
Status Status of task execution progress
Creationoptions Behavior of task creation and execution
Id Task Thread ID
IsCanceled Whether the task was canceled
IsCompleted Whether the task is complete
isfaulted Whether the task failed
Result Task return value, which applies only to tasks that have return parameters

ContinueWith () Perform another task after the thread finishes executing
Getawaiter () Get waiting for this thread to wait
Start () Initiate a task
Wait () The task thread that is currently calling wait Waits

These are common.

Task callback

Let's get to know TaskFactory.

CancellationToken Task Cancellation Token
Continuationoptions The literal meaning of the task continuation selection. Official comments are not flattering. It's about Continuewhenall and Continuewhenany.
Creationoptions Specifies the default creation option for this task factory. (Task execution order, whether long time execution ...) )
Scheduler Task Scheduler for the task factory. Represents an object that handles low-level work that queues a task to a thread.

Continuewhenall

Create a continuation task that will start immediately after all the tasks in the provided group have been completed. First parameter P1: The thread list, which is the thread to execute

( must have taskfactory created calling Continuewhenall) the second parameter P2: callback function

(the first parameter of the callback function is the first argument P1, the second parameter of the callback function is the return value, defined by taskfactory<>).

The execution order P1 executed first and then P2 executed. TaskFactory's task is random execution

Continuewhenany Create a continuation task that will start immediately after any tasks in the provided group have been completed.
FromAsync

Creates a task that executes an end method function when the specified System.IAsyncResult completes. (The official explanation is a little bit around actually

it allows you to convert an asynchronous task to a task, the return value is a task, and finally a callback function is executed .

Spit The Groove, the official translation is not all computer translation.

StartNew Create an open task

Task Cancel

Mainly the class CancellationTokenSource

Definition: Notify System.Threading.CancellationToken that it should be canceled.

You can cancel it now, and you can set the time to cancel.

CancellationTokenSource CLT =NewCancellationTokenSource (); TaskFactory TF=NewTaskFactory (CLT. Token); TF. StartNew (()={    inttemp =0;  for(inti =0; I <10000; i++) {Thread.Sleep (Ten); if(!CLT. iscancellationrequested) {Temp+=i; }        Else        {             Break; }} Console.WriteLine (temp);}); Thread.Sleep ( $); clt. Cancel ();
View Code
Task return value

With the return value, the return value type is to be specified with the generic type.

task<intnew task<int5); T.start (); Console.WriteLine (T.result); TaskFactory<intnew taskfactory<int>(); var  return 6 ; }); Console.WriteLine (TFT. Result);
View Code

Finally, the results are obtained by Task.result. This operation will be stuck on the thread, waiting for the result to go back.

Parallel Parallel tasks

1. Parallel definition: Provides support for parallel loops and regions. Static classes, static methods. He is a task-based, thread pool.

In fact, it is the operation of the Loop task, but the task of the loop is executed in parallel, no one order, but the loop will wait for them to end.

Parallel.For

Parallel.ForEach

Parallel.invok

Advantages: The main thread will also participate in the calculation, the disadvantage: it will WaitAll

2. Parallelloopresult definition: Provides the completion status of the execution System.Threading.Tasks.Parallel loop. is actually the return value of for and foreach

3, parallelloopstate definition: can be used to make the iteration of the System.Threading.Tasks.Parallel loop interacting with other iterations. Instances of this class are provided to each loop by the Parallel class, and instances cannot be created in your user code.

He can let the loop exit, notice. (Just like the bread in the For loop)

4. ParallelOptions definition: The option to store the operation of the method used to configure the System.Threading.Tasks.Parallel class.

////Summary://Gets or sets the System.Threading.CancellationToken associated with this System.Threading.Tasks.ParallelOptions instance. ////return Result://the token associated with this instance.  PublicCancellationToken CancellationToken {Get;Set; }////Summary://Gets or sets the maximum degree of parallelism allowed for this System.Threading.Tasks.ParallelOptions instance. ////return Result://An integer that represents the maximum degree of parallelism. ////Exception://T:System.ArgumentOutOfRangeException://The property is set to a value of 0 or less than-1.  Public intmaxdegreeofparallelism {Get;Set; }////Summary://Gets or sets the System.Threading.Tasks.TaskScheduler associated with this System.Threading.Tasks.ParallelOptions instance. Set this property to//NULL to indicate that the current scheduler should be used. ////return Result://the Task Scheduler associated with this instance.  PublicTaskScheduler TaskScheduler {Get;Set; }
View Code

Can cancel the task, the number of parallel (in the loop in a parallel execution of the number of tasks, when the task volume is relatively large, be sure to specify this value, or the computer may not survive. But he is based on the thread pool, and the thread pool will help us control it, but it will still be the card computer. Parallel quantity control, which causes the thread to be round round, each round the first thread ID is the same, with the main path ID)

5. Summary

The Parallel.For () and Paraller.foreach () methods call the same code in each iteration, whereas the Parallel.Invoke () method allows different methods to be called simultaneously. Parallel.ForEach () is used for data parallelism, and Parallel.Invoke () is used for task parallelism;

Await Async

1. Appearance of introduction

c#5.0 C # language version

. NET Fromwork 4.5 Framework class library version FCL

clr4.0 CLR Version

Await async He is a grammatical sugar. What is syntax sugar, is C # alive. NET fromwork changes but the CLR has not changed.

Generics are not syntactic sugars, and when he appears, the CLR rewrites, that is, where generics are used, corresponding type methods are generated.

No task, no await async.

2. Principle

is a syntactic sugar, using a state machine concept, the compiler compiles a part of the code as a callback, the state machine is this one after execution, Movenest executes the next callback. is to await a layer of nesting on it.

3. Use

An await can only appear in front of the task, and the code behind the await becomes the callback for the task. The asynchronous callback is written out quickly

The return value can only be a void task task<> the task<> return value is recommended.

This article code download

Multithreading-task, Await/async

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.