Func, Action, async, and await usage in C # task

Source: Internet
Author: User

Before you say ASNC and await, explain the use of the Func and action delegates, the basis of task tasks

1. Func

Func is a delegate, which is added in 3.5, 2.0 inside we use the delegate is located under the System.core namespace, using a delegate can improve efficiency, such as in reflection can compensate for the loss of performance of the Delegate,func.

The function of action<t> and func<t,tresult> is the same, just action<t> no return type,

Func<t,t,result>: parameter, return type
Action, there is neither return nor parameter,

Func<t,tresult>
Forms of expression are divided into the following types:

1. Func<t,tresult>
2. Func<t,t1,tresult>
3. Func<t,t1,t2,tresult>
4. Func<t,t1,t2,t3,tresult>
5. Func<t,t1,t2,t3,t4,tresult>

Say the meaning of each parameter separately, TResult said
The type represented by the value returned by the delegate, T,T1,T2,T3,T4 represents the parameter type of the method called by the delegate,

The following are examples of use:

1func<int,BOOL> MyFunc =NULL;//All Variables2 3MyFunc = x = =CheckIsInt32 (x);4 //A lambda expression is used where the delegate encapsulates the method5 6 Private BOOLCheckIsInt32 (intPars//Encapsulated Method7 {8     returnPars = =5;9 }Ten  One BOOLOK = MyFunc (5);//Invoke Delegate


msdn:http://msdn.microsoft.com/zh-cn/library/bb534303 (vs.95). aspx

2. Action

But what if we need to encapsulate a method that does not return a value? Just use action!.

can use
Action<t1, T2, T3, t4> delegates pass the method as a parameter without explicitly declaring a custom delegate. The encapsulated method must correspond to the method signature defined by this delegate. That is, the encapsulated method must have four parameters that are passed to it by value and cannot return a value. (in C #, the method must return void.) In Visual Basic, you must pass a Sub ... END SUB structure to define it. Typically, this method is used to perform an operation.

Use the same method as Func!

Action: There is neither return nor parameter, using the following method:

1 null; // Define Action 2 3 action =  checkisvoid;   The encapsulation method requires only the name of the method 45 action (); // called

msdn:http://msdn.microsoft.com/zh-cn/library/bb548654 (vs.95). aspx

Summarize:

Using func<t,tresult> and action<t>,action instead of delegate is all about simplifying the code, using less code to achieve the same effect, without requiring us to display a delegate for the Declaration.

The last parameter of func<t,tresult> is always the return type, while action<t> is not a return type, and the action is not returned type and parameter input.

3. Task

asynchronous programming with Async and Await (a good article on MSDN) : https://msdn.microsoft.com/zh-cn/library/hh191443 (v=vs.120)

Task Basic usage: C # Threading Knowledge-using task to perform asynchronous operations

Task and await combined return values see:. NET (C #): Await the Async method that returns a task

Task insights See: Use of C # tasks

Summary: Task provides a new multithreaded multi-tasking usage that achieves the effect of using threads, but specifically how the allocation thread is controlled by the. NET bottom line, so that the performance is good and the efficiency is high, we only need to focus on the business logic and have the function of the return value that is not available on the front thread (can be handled by callback events) While in the task is simply using await to use, the await task is equivalent to synchronous call task, and there will be a return value, only in the writing need to pay attention to the use of async, task,func, action and so on keyword, novice may be very confused, The following example is an example of a simple task use, the Novice notes!!!

1 Static voidMain (string[] args)2 {3     //asynchronous methods, where await can perform task asynchronous tasks, otherwise as synchronous execution4 test ();5     //The next output, because asynchronously enters the task, executes the code below the current thread synchronously6Log"Main: After calling Test");7 Thread.Sleep (timeout.infinite);8 }9 Ten //The Main method does not allow async, so we use await in this method One Static Async voidTest () A { -     //first output, not yet into task -Log"before Test:await"); the     //the await content is appended to the target Doo task, and test returns immediately, while Doo enters another task to execute the -Log"The result of the Doo task:"+awaitDoo ()); -     //the current code will not be executed until the completion of the task above await -Log"after test:await"); + } - //returns the Async method of a task, a standard asynchronous task task method with a return value + Static Asynctask<int>Doo () A { at     //To put it simply, the use of await in async is the way in which task tasks are executed synchronously in a synchronous manner, and task tasks execute one after the other. -     varRes1 =awaitTask.run (() = {Thread.Sleep ( +); Log"awaited Task1 execution");return 1; }); -     varRes2 =awaitTask.run (() = {Thread.Sleep ( +); Log"awaited Task2 execution");return 2; }); -     varRes3 =awaitTask.run (() = {Thread.Sleep ( +); Log"awaited Task3 execution");return 3; }); -  -     //do not use await: thread pool multi-threading, the current task does not wait for this to finish, because it is not an await, just another thread opened inThreadPool.QueueUserWorkItem (_ = -     { toThread.Sleep ( +); +Log"ThreadPool.QueueUserWorkItem: Thread pool multithreaded execution"); -     }); the  *     //do not use Await:task Multi-threading, the current task will not wait for this to finish, because it is not an await, but also open a task $Task.run (() =Panax Notoginseng     { -Thread.Sleep ( +); theLog"Task.Run:Task multithreaded Execution"); +  A     }); the       +     returnRes1 + Res2 +Res3; - } $ //Output Method: Displays the current thread number and output information $ Static voidLogstringmsg) - { -Console.WriteLine ("Thread {0}: {1}", Thread.CurrentThread.ManagedThreadId, msg); the}

The results of the implementation are as follows:

4. Async, Await

This is a feature of. NET 4.5, so the requirement is minimal. NET version is 4.5.

See a lot of friends still use the thread to use asynchronous multithreaded operations, basically do not see the use of async, await asynchronous programming. Each their own, actually all can. As long as the correct use of the line, but still wrote this article recommended that you use Async, Await. The reason is that you can do asynchronous programming just as you would write synchronous methods. The code is very clear, just like writing normal code, without the relationship of how to do asynchronous programming, but also many novice programmers can also be programmed asynchronously. Here is an asynchronous example using thread multithreading implementation, and an asynchronous example using async and await, and then we'll take a quick and easy understanding of the technical notes for async and await.

Thread multithreaded Asynchronous Programming example
classprogram{Static voidMain (string[] args) {Console.WriteLine ("The main thread test begins :"); Thread th=NewThread (Thmethod); Th.        Start (); Thread.Sleep ( +); Console.WriteLine ("end of Main thread test :");    Console.ReadLine (); }      Static voidThmethod () {Console.WriteLine ("Asynchronous execution Start");  for(inti =0; I <5; i++) {Console.WriteLine ("Asynchronous Execution"+ i.tostring () +".."); Thread.Sleep ( +); } Console.WriteLine ("Asynchronous execution Complete"); }}

  

The above code runs the effect as

Asynchronous programming using Async and await

1 Static voidMain (string[] args)2 {3Console.WriteLine ("The main thread test begins :");4 Asyncmethod ();5Thread.Sleep ( +);6Console.WriteLine ("end of Main thread test :");7 console.readline ();8 }9 Ten Static Async voidAsyncmethod () One { AConsole.WriteLine ("Start Async Code"); -     varresult =awaitMyMethod (); -Console.WriteLine ("Asynchronous code Execution complete"+result. ToString ()); the } -  - Static Asynctask<int>MyMethod () - { +      for(inti =0; I <5; i++) -     { +Console.WriteLine ("Asynchronous Execution"+ i.tostring () +".."); A         awaitTask.delay ( +);//simulate time-consuming operations at     } -     return  -; -}

Operating effect:

It is obvious that we have written the asynchronous method as well as the synchronous method, and the code is clearer.

You can use the AWAIT keyword internally only if you have async. an async method can have a return type of Task, task<>, or void;

The await keyword is a method for returning a value that is a "waiting" type (awaitable)

Func, Action, async, and await usage in C # 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.