Use C # Task in Func, Action, Async and Await knowledge of C # thread - Use Task to perform asynchronous operations .NET (C #): await the return of async method Task

Before saying Asnc and Await, first explain the usage-based Func and Action delegate, Task task

1. Func

Func is a commission, which is inside the new 3.5, 2.0 which we are entrusted with the use Delegate, Func located in System.Core namespace, using the delegate can improve efficiency, for example, in reflection can make up for the loss of reflected performance.

Action <T> and Func <T, TResult> function is the same, but Action <T> does not return type,

Func <T, T, the Result>: there are parameters, it returns the type of
the Action, then neither returns nor parameter ,

Func <T, TResult> 
manifestations divided into the following:

1. FUNC <T, TResult>
2. FUNC <T, Tl, TResult>
. 3. FUNC <T, Tl, T2, TResult>
. 4. FUNC <T, Tl, T2, T3, TResult>
. 5. Func <T, T1, T2, T3, T4, TResult>

respectively, said the significance of each parameter, TResult indicates 
the parameter type delegate returned value represents, T, T1, T2, T3 , T4 representation delegate invoked type,

the following examples are used:

Copy the code
1 Func <int, bool> myFunc = null; // all variables 
 2 
 . 3 = X = the myFunc> CheckIsInt32 (X); 
 . 4 to local delegate // packaging method using a Lambda expression 
 . 5 
 . 6 Private BOOL CheckIsInt32 (int Pars) // encapsulated method 
 . 7 { 
 . 8 == return Pars. 5; 
 . 9} 
10 
. 11 BOOL the myFunc OK = (. 5); // call to delegate
Copy the code


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

2. Action

But if we need a method that does not return a value package, increasing it to do it? On the use of Action!

You can use
Action <T1, T2, T3, T4> delegate transmission method as a parameter instead of explicitly declared custom delegate. The method of packaging must be defined with this method signature delegate correspond. That is, the method of the package must have four parameters are passed to it a value, and can not return a value. (In C #, the method must return void. In Visual Basic, it must be defined by the Sub ... End Sub structure.) In general, this method is used to perform an action.

Use and Func similar!

The Action: neither return nor parameter, used as follows:

1 Action action = null; // definition of Action 
2 
. 3 Action = CheckIsVoid; // name packaging method, the method requires only 
. 4 
. 5 Action (); // call

 

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

to sum up:

Use Func <T, TResult> and Action <T>, Action without using Delegate to simplify the code actually uses less code to achieve the same effect, we do not need to display a statement delegate.

Func <T, TResult> last parameter is always return type, and the Action <T> is the type of no return, and no Action input parameter and return type.

 

3. Task

Async and Await use of asynchronous programming (good article in msdn):   https://msdn.microsoft.com/zh-cn/library/hh191443(v=vs.120)

Task basic use:  C # threading knowledge - Task execution using asynchronous operation

Task binding and await the return value, see:  .NET (C #): Task await the method returns async

Task-depth understanding see:  Use of C # Task

 

Summary: Task provide a new, similar multi-tasking multi-threaded usage, to the effect of the use of threads, but how distribution is controlled by the underlying thread .net, so good performance, high efficiency, we only need to focus on business logic, while with thread before the function return value not available (can be handled by the callback event), and in the Task simply using await in use, await the task is equivalent to calling task synchronization, but there will be a return value, but in writing areas requiring attention using async, task, func, action and so on keywords, novices might be confused, the following example is a simple task using the example of someone new to the comment !!!

Copy the code
Static void the Main. 1 (String [] args) 
 2 { 
 . 3 // asynchronous method, which can perform the task using await asynchronous tasks otherwise performed as synchronization 
 . 4 Test (); 
 . 5 // output secondly, due to the asynchronous task into the task, on the execution of the current thread synchronization code below 
 6 log ( "Main: after calling the Test"); 
 7 Thread.Sleep (Timeout.Infinite); 
 8} 
 9 
10 // Main method does not add async, so we use this method with await 
static void Test the async. 11 () 
12 is { 
13 is output // first, not yet entered Task 
14 log ( "Test: before await"); 
the contents after 15 // await Task will be added after target doo, and test immediately returned, and doo is entering another task performed 
16 log ( "doo result of the task:" + await doo ()); 
17 // will wait until after the implementation of the current code to perform tasks await the completion of the above 
18 log ( "test: await later"); 
. 19} 
20 is a task // return the async method, a standard asynchronous task with the task the method returns values
The async static Task 21 is <int> Doo ()  
22 is {
23 is // Briefly, async await use asynchronous method is performed in a synchronized manner Task task, task task executed one after another. 
24 await Task.Run var RES1 = (( ) => {Thread.Sleep (1000) ; log ( "awaited Task1 execution"); return. 1;}); 
25 var RES2 the await Task.Run = (() => {the Thread.Sleep (1000); log ( " awaited Task2 execution "); return 2;}); 
26 is the await Task.Run var RES3 = (() => {the Thread.Sleep (1000); log (" awaited Task3 execution "); return. 3;}); 
27 
28 // do not use await: multi-threaded thread pool, and so the current task is not executed, because it is not the await, but had opened a thread 
29 the ThreadPool.QueueUserWorkItem (_ => 
30 { 
31 is the Thread.Sleep (1000); 
32 log ( "ThreadPool.QueueUserWorkItem: multithreaded execution thread pool"); 
33}); 
34 
35 // do not use await: task multithreading, such as the current task is not executed, because not await, but had opened up a task 
36 task.Run(() =>
37     {
The Thread.Sleep 38 is (1000); 
39 log ( "Task.Run: the Task multithreaded execution"); 
40 
41 is}); 
42 is    
43 is return RES1 RES2 + + RES3; 
44 is} 
45 // output method: displays the current thread number and output 
46 is static void log (String MSG) 
47 { 
48 Console.WriteLine ( "thread 0} {: {}. 1", Thread.CurrentThread.ManagedThreadId, MSG); 
49}
Copy the code

 

Execution results are as follows:

 

4. Async、Await

This is characteristic of .NET 4.5, it requires a minimum .NET version 4.5.

See a lot of friends still use the Thread to the use of asynchronous multi-threaded operation, basically do not see any use Async, Await for asynchronous programming. All have love it, actually can be. As long as the proper use of the line, but still I wrote this article recommend the use of Async, Await. The reason is this: you can write like synchronous methods to asynchronous programming. Code is very clear, just write common code, like how to do asynchronous programming relationship, but also a lot of junior programmer can asynchronously programmed. Here is an example of using asynchronous Thread multithreading, and an asynchronous example Async and Await use, then we'll simply understand the relevant technical notes under the Async and Await.

Thread multi-threaded asynchronous programming examples

Copy the code
Program class 
{ 
    static void the Main (String [] args) 
    { 
        Console.WriteLine ( "main thread start of the test .."); 
        the Thread new new TH = the Thread (ThMethod); 
        th.Start (); 
        the Thread.Sleep (1000); 
        Console .WriteLine ( "main thread end of the test .."); 
        Console.ReadLine (); 
    } 
 
 
    static void ThMethod () 
    { 
        Console.WriteLine ( "asynchronous execution start"); 
        for (int I = 0; I <. 5; I ++) 
        { 
            Console.WriteLine ( "asynchronous execution" i.ToString + () + ".."); 
            the Thread.Sleep (1000); 
        } 
        Console.WriteLine ( "asynchronous execution complete"); 
    } 
}
Copy the code

 

  

Code is run to the following figure

 

 

Async and Await using asynchronous programming

 

Copy the code
Static void the Main. 1 (String [] args) 
 2 { 
 . 3 Console.WriteLine ( "main thread start of the test .."); 
 . 4 AsyncMethod (); 
 . 5 the Thread.Sleep (1000); 
 . 6 Console.WriteLine ( "main thread end of the test .. "); 
 . 7 Console.ReadLine (); 
 . 8} 
 . 9 
10 static void AsyncMethod the async () 
. 11 { 
12 is Console.WriteLine (" asynchronous start Code "); 
13 is the await MyMethod var Result = (); 
14 Console.WriteLine ( "asynchronous code is finished" + result.ToString ()); 
15} 
16 
. 17 the async static the Task <int> MyMethod () 
18 is { 
. 19 for (int I = 0; I <. 5; I ++) 
20 is { 
21 is Console.WriteLine ( "asynchronous execution" + i.ToString () + ".. ");
22 await Task.Delay (1000); // analog consuming operations ");
23     }
24     return 100;
25 }
Copy the code

 

running result:

 

Obvious we just write the same synchronization method, completed the preparation of the asynchronous method, the code clearer.

Only have to use async await keyword inside. Asynchronous method may have Task, Task <> or void return type;

keyword is used to await the return value is "waiting" type (awaitable) method

 

Once a cloud drifting across the sky, without leaving a trace

Before saying Asnc and Await, first explain the usage-based Func and Action delegate, Task task

1. Func

Func是一种委托,这是在3.5里面新增的,2.0里面我们使用委托是用Delegate,Func位于System.Core命名空间下,使用委托可以提升效率,例如在反射中使用就可以弥补反射所损失的性能。

Action<T>和Func<T,TResult>的功能是一样的,只是Action<T>没有返类型,

Func<T,T,Result>:有参数,有返回类型
Action,则既没有返回也没有参数,

Func<T,TResult> 
的表现形式分为以下几种:

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>

分别说一下各个参数的意义,TResult表示 
委托所返回值 所代表的类型, T,T1,T2,T3,T4表示委托所调用的方法的参数类型,

以下是使用示例:

Copy the code
 1 Func<int, bool> myFunc = null;//全部变量
 2 
 3 myFunc = x => CheckIsInt32(x); 
 4 //给委托封装方法的地方 使用了Lambda表达式
 5 
 6 private bool CheckIsInt32(int pars)//被封装的方法
 7 {
 8   return pars == 5;
 9 }
10 
11 bool ok = myFunc(5);//调用委托
Copy the code


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

2. Action

但是如果我们需要所封装的方法不返回值,增么办呢?就使用Action!

可以使用
Action<T1, T2, T3, T4>委托以参数形式传递方法,而不用显式声明自定义的委托。封装的方法必须与此委托定义的方法签名相对应。也就是说,封装的方法必须具有四个均通过值传递给它的参数,并且不能返回值。(在 C# 中,该方法必须返回 void。在 Visual Basic 中,必须通过 Sub…End Sub 结构来定义它。)通常,这种方法用于执行某个操作。

使用方法和Func类似!

Action:既没有返回,也没有参数,使用方式如下:

1 Action action = null;//定义action
2 
3 action =  CheckIsVoid;//封装方法,只需要方法的名字
4 
5 action();//调用

 

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

总结:

使用Func<T,TResult>和Action<T>,Action而不使用Delegate其实都是为了简化代码,使用更少的代码达到相同的效果,不需要我们显示的声明一个委托。

Func<T,TResult>的最后一个参数始终是返回类型,而Action<T>是没有返回类型的,而Action是没有返回类型和参数输入的.

 

3. Task

使用 Async 和 Await 的异步编程(msdn的好文章) :  https://msdn.microsoft.com/zh-cn/library/hh191443(v=vs.120)

Task基本使用: C# 线程知识--使用Task执行异步操作

Task和await结合返回值见: .NET(C#):await返回Task的async方法

Task深入了解见: C# Task的使用

 

总结: Task提供一种新的类似多线程的多任务的用法, 达到使用线程的效果,但具体怎么分配线程由.net底层控制,这样性能好,效率也高,我们只需要专注业务逻辑, 同时具备以前线程不具备的返回值的功能(可以通过回调事件来处理),而在Task中只是简单的使用await来使用, await的task相当于同步的调用task, 同时会有返回值,只是在书写方面需要注意async, task,func, action等等关键字的使用,新手可能很困惑, 下面的例子就是一个简单的task使用例子,新手注意注释!!!

Copy the code
 1 static void Main(string[] args)
 2 {
 3     //异步方法, 当中使用await可以执行task异步任务,否则当作同步执行
 4     test();
 5     //其次输出,因为异步进入task任务了,就同步执行当前线程下面的代码
 6     log("Main:调用test后");
 7     Thread.Sleep(Timeout.Infinite); 
 8 }
 9 
10 //Main方法不允许加async,所以我们用这个方法使用await
11 static async void test()
12 {
13     //最先输出,还没有进入task
14     log("test: await之前");
15     // await后的内容会被加在目标doo的Task的后面,然后test马上返回,而doo则是进入了另一个任务执行了
16     log("doo的Task的结果: " + await doo());
17     // 会等到上面await执行的任务完成后才会执行当前代码
18     log("test: await之后");
19 }
20 //返回Task的async方法, 一个标准的带返回值的异步task任务方法
21 static async Task<int> doo()
22 {
23     // 简单的说, async中使用await就是异步中以同步方式执行Task任务的方法,task任务一个接一个执行.
24     var res1 = await Task.Run(() => { Thread.Sleep(1000); log("Awaited Task1 执行"); return 1; });
25     var res2 = await Task.Run(() => { Thread.Sleep(1000); log("Awaited Task2 执行"); return 2; });
26     var res3 = await Task.Run(() => { Thread.Sleep(1000); log("Awaited Task3 执行"); return 3; });
27 
28     //不使用await:线程池多线程, 当前task不会等这个执行完,因为不是await,只是又开启了一个线程
29     ThreadPool.QueueUserWorkItem(_ =>
30     {
31         Thread.Sleep(1000);
32         log("ThreadPool.QueueUserWorkItem: 线程池多线程执行");
33     });
34 
35     //不使用await:Task多线程, 当前task不会等这个执行完,因为不是await,只是又开启了一个任务
36     Task.Run(() =>
37     {
38         Thread.Sleep(1000);
39         log("Task.Run: Task多线程执行");
40 
41     });
42    
43     return res1 + res2 + res3;
44 }
45 //输出方法:显示当前线程号和输出信息
46 static void log(string msg)
47 {
48     Console.WriteLine("线程{0}: {1}", Thread.CurrentThread.ManagedThreadId, msg);
49 }
Copy the code

 

执行结果如下:

 

4. Async、Await

这个是.NET 4.5的特性,所以要求最低.NET版本为4.5。

看很多朋友还是使用的Thread来使用异步多线程操作,基本上看不见有使用Async、Await进行异步编程的。各有所爱吧,其实都可以。只要正确使用就行,不过还是写了这篇文章推荐大家使用Async、Await。 原因就是:可以跟写同步方法一样去异步编程。代码则就非常的清晰,就跟写普通的代码一样,不用关系如何去异步编程,也让很多初级程序员也能够异步编程了。下面是一个使用Thread 多线程实现的异步例子,以及一个使用Async与Await的异步例子,接下来我们再简单理解下Async与Await的相关技术说明。

Thread多线程异步编程例子

Copy the code
class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("主线程测试开始..");
        Thread th = new Thread(ThMethod);
        th.Start();
        Thread.Sleep(1000);
        Console.WriteLine("主线程测试结束..");
        Console.ReadLine();
    }
 
 
    static void ThMethod()
    {
        Console.WriteLine("异步执行开始");
        for (int i = 0; i < 5; i++)
        {
            Console.WriteLine("异步执行" + i.ToString() + "..");
            Thread.Sleep(1000);
        }
        Console.WriteLine("异步执行完成");
    }
}
Copy the code

 

  

以上代码运行效果如下图

 

 

使用Async与Await进行异步编程

 

Copy the code
 1 static void Main(string[] args)
 2 {
 3     Console.WriteLine("主线程测试开始..");
 4     AsyncMethod();
 5     Thread.Sleep(1000);
 6     Console.WriteLine("主线程测试结束..");
 7     Console.ReadLine();
 8 }
 9 
10 static async void AsyncMethod()
11 {
12     Console.WriteLine("开始异步代码");
13     var result = await MyMethod();
14     Console.WriteLine("异步代码执行完毕" + result.ToString());
15 }
16 
17 static async Task<int> MyMethod()
18 {
19     for (int i = 0; i < 5; i++)
20     {
21         Console.WriteLine("异步执行" + i.ToString() + "..");
22         await Task.Delay(1000); //模拟耗时操作
23     }
24     return 100;
25 }
Copy the code

 

running result:

 

Obvious we just write the same synchronization method, completed the preparation of the asynchronous method, the code clearer.

Only have to use async await keyword inside. Asynchronous method may have Task, Task <> or void return type;

keyword is used to await the return value is "waiting" type (awaitable) method

 

Guess you like

Origin www.cnblogs.com/wwwbdabc/p/11652592.html