(Task)任务异步(TAP)的使用

任务有返回值例子:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 
 8 namespace Demo
 9 {
10     class Program
11     {
12 
13         static void Main(string[] args)
14         {
15 
16             System.Threading.Tasks.Task<string> task = Task.Factory.StartNew<string>(Test);
17 
18             Console.WriteLine("Result:" + task.Result);
19             Console.WriteLine("Status:" + task.Status);
20             Console.WriteLine("IsFaulted:" + task.IsFaulted);
21             Console.WriteLine("IsCompleted:" + task.IsCompleted);
22             Console.WriteLine("IsCanceled:" + task.IsCanceled);
23             Console.ReadKey();
24         }
25 
26         public static string Test()
27         {
28             Console.WriteLine("调用test方法:"+"ddddfdfd");
29             return "调用异步方法返回的结果";
30         }
31 
32     }
33 }

下图是上面的代码的运行结果:

 

没有返回值的任务:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 
 8 namespace Demo
 9 {
10     class Program
11     {
12 
13         static void Main(string[] args)
14         {
15 
16             System.Threading.Tasks.Task task = Task.Factory.StartNew(Test);
17 
18             Console.WriteLine("Status:" + task.Status);
19             Console.WriteLine("IsFaulted:" + task.IsFaulted);
20             Console.WriteLine("IsCompleted:" + task.IsCompleted);
21             Console.WriteLine("IsCanceled:" + task.IsCanceled);
22             Console.ReadKey();
23         }
24 
25         public static void Test()
26         {
27             Console.WriteLine("调用test方法:"+"ddddfdfd");
28         }
29 
30     }
31 }

下面是上述代码运行的结果:

posted @ 2016-07-12 00:00  赛跑的蜗牛  阅读(419)  评论(0编辑  收藏  举报