On the Task Usage

Task is used to achieve multi-threaded class, when in previous versions have Thread and ThreadPool, why it is proposed Task class, because the direct operation of Thread and ThreadPool, pass parameters to the thread, gets the return value of the thread when the start-stop and thread are very troublesome, so Microsoft's engineers have been the repackaging of thread, this is Task, so to speak Task is built on top of thread,

So when multi-threaded Task is our first choice.

The Task class and Task <TResult> class, which is a generic version of the former. TResult type Task invoked method's return value.

The main difference is that the constructor accepts Task Action parameter is commissioned, the Task <TResult> accepted Func <TResult> delegate

1 Task(Action) 
2 Task<TResult>(Func<TResult>)  

A, Task statement

Task statement in two ways:

a, declared by the new way

1 Task objTask = new Task();

b. to declare by way of Task.Factory.StartNew

1   Task.Factory.StartNew(MyMethod);

The difference between these two statements ways, the first way to declare open thread must use objTask.Start (), which by the way is not Task.Factory.StartNew.

 Two, Task common method

 a. Start a task

1 static void Main(string[] args) 
2         { 
3             Task Task1 = new Task(() => Console.WriteLine("Task1")); 
4             Task1.Start(); 
5             Console.ReadLine(); 
6         } 

By way of example of a Task object, then the Start, quite satisfactory in this way, but in practice, usually more convenient and efficient manner

Task.Run(() => Console.WriteLine("Foo"));

This run directly Task, unlike the above methods also need to call the Start ();

Task.Run method is Task class static methods accepted parameters is commissioned. The return value is for the Task object.

Task.Run(Action)

Task.Run<TResult>(Func<Task<TResult>>)

There is also a constructor Task overloaded function as follows:

Task Constructor (Action, TaskCreationOptions), Task generic version of the corresponding function has a similar configuration. TaskCreationOptions parameter indicates Task creation and execution of optional behavior. Commonly used parameters LongRunning.

b. Tasks waiting

By default, Task task performed by the asynchronous thread pool, Task want to know whether the task is completed, the property may be obtained by Task.IsComplated

You can also use Task.Wait () method to wait for the completion thread, Task.Wait () method blocks the current thread.

 1 static void Main(string[] args) 
 2         { 
 3             Task Task1=Task.Run(() => { Thread.Sleep(5000); 
 4             Console.WriteLine("Foo"); 
 5                 Thread.Sleep(5000); 
 6             }); 
 7             Console.WriteLine(Task1.IsCompleted); 
 8             Task1.Wait();//阻塞当前线程 
 9             Console.WriteLine(Task1.IsCompleted); 
10         }

Also need to say is, Wait method has a reconstruction method, the following signature: public bool Wait (int millisecondsTimeout), accepts a time. Returns true if completed within the set time, otherwise false. The following code:

 1 static void Main(string[] args) 
 2         { 
 3             Task Task1=Task.Run(() => { Thread.Sleep(5000); 
 4             Console.WriteLine("Foo"); 
 5                 Thread.Sleep(5000); 
 6             }); 
 7  
 8             Console.WriteLine("Task1.IsCompleted:{0}",Task1.IsCompleted); 
 9             bool b=Task1.Wait(2000); 
10             Console.WriteLine("Task1.IsCompleted:{0}", Task1.IsCompleted); 
11             Console.WriteLine(b); 
12             Thread.Sleep(9000); 
13             Console.WriteLine("Task1.IsCompleted:{0}", Task1.IsCompleted); 
14        }

The resulting output is:

C. to obtain a return value

To get a return value, it is necessary to use the generic version of the Task. Speaking of the return value would have to say that Task async and await keywords up.

When the async function flag, the return value must be void, Task, Task <T>, when the return value Task <T>, T internal function returns only type, the compiler will automatically packaged Task <T> Type

await keyword must be used within the function with async mark. for example:

 1 static void Main(string[] args)
 2         {
 3             Console.WriteLine("调用主线程");
 4             Task<string> s = Testasync();
 5             Console.WriteLine(s.Result);
 6             Console.ReadKey();
 7 
 8         }
 9          static async Task<string> Testasync()
10         {
11             Console.WriteLine("运行Task之前" + Thread.CurrentThread.ManagedThreadId);
12 
13             Task<string> t= Task.Run<string>(() => 
14             {
15                 Console.WriteLine("运行Task" + Thread.CurrentThread.ManagedThreadId);
16                 Thread.Sleep(9000);
17                 return "我是测试线程";
18             });
19             Console.WriteLine("运行Task之后" + Thread.CurrentThread.ManagedThreadId);
20             var result = await t;
21             return result;
22         }

As can be seen from the results:

1) In the async method identified body inside, If it does not await keyword, then this method calls ordinary method and no difference (that is async and await occur in pairs, not await the async makes no sense)

(2) in the async method identified body inside, before the await keyword appears, or call the main thread of the order until the keyword will await the emergence of thread blocks.

(3) await completion of keywords can be understood as the await execution method, in addition to marked with the keyword async method, but also can mark Task object that represents the thread is finished waiting. So await keyword is not directed to a method async, but returned to us for Task async method.

D. continuation of the mission

The so-called continuation of the mission, that continue to perform the task after task execution is completed, there are two ways

First, the use of a method using GetAwaiter. GetAwaiter TaskAwaiter method returns a structure that has a OnCompleted event, just to OnCompleted event assignment, you can call the event upon completion. 

 1 static void Main(string[] args) 
 2         { 
 3             Task<int> Task1 = Task.Run<int>(() => { return Enumerable.Range(1, 100).Sum(); }); 
 4             var awaiter = Task1.GetAwaiter(); 
 5             awaiter.OnCompleted(() => 
 6             { 
 7                 Console.WriteLine("Task1 finished"); 
 8                 int result = awaiter.GetResult(); 
 9                 Console.WriteLine(result); // Writes result 
10             }); 
11             Thread.Sleep(1000); 
12         }

Second, using the method ContinueWith

Any natural ContinueWith Task returns a type. There are many ways ContinueWith overloading, a generic version of the count, almost 40 of these. One of the most common, is to accept a Func or Action delegate, and that delegate these parameters are passed in the first Task type, which can access the previous Task objects. Example: 

1 static void Main(string[] args) 
2         { 
3             Task<int> Task1 = Task.Run<int>(() => {return Enumerable.Range(1, 100).Sum(); }); 
4             Task1.ContinueWith(antecedent => { 
5             Console.WriteLine(antecedent.Result); 
6             Console.WriteLine("Runing Continue Task"); 
7 }); 
8             Thread.Sleep(1000); 
9         }

E, delayed task

Task.Delay () method is equivalent to the Thread.Sleep asynchronous ();

 

Guess you like

Origin www.cnblogs.com/Artist007/p/11538437.html