码迷,mamicode.com
首页 > 其他好文 > 详细

async & await 异步编程小示例,一看就懂

时间:2015-06-10 00:56:11      阅读:114      评论:0      收藏:0      [点我收藏+]

标签:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading;
 6 using System.Threading.Tasks;
 7 
 8 namespace ConAppAsync
 9 {
10     class Program
11     {
12 
13         //第一步,创建一个普通的耗时的方法
14         static string Greeting(string name)
15         {
16             Thread.Sleep(3000);
17             return String.Format("Hello, {0}", name);
18         }
19 
20         //第二步,用一个异步方法包装上面的方法
21         static Task<string> GreetingAsync(string name)
22         {
23             return Task.Run<string>(() =>
24             {
25                 return Greeting(name);
26             });
27         }
28 
29         //第三步,再创建一个能调用上面的异步方法的方法, 加关键字 async
30 
31         private async static void CallWithAsync()
32         {
33             //some other tasks
34 
35             string result = await GreetingAsync("王海滨");
36 
37             //we can add multiple "await" in same "async" method
38             string result1 = await GreetingAsync("Ahmed");
39             string result2 = await GreetingAsync("Every Body"); 
40             Console.WriteLine(result+result1+result2);
41         }
42 
43         static void Main(string[] args)
44         {
45             //最后在主入口调用上面的方法,和调用普通方法一样
46             CallWithAsync();
47             int length = 100;
48             for (int i = 0; i < length; i++)
49             {
50                 Console.WriteLine(i);
51             }
52             Console.ReadKey();
53         }
54     }
55 }

 

async & await 异步编程小示例,一看就懂

标签:

原文地址:http://www.cnblogs.com/wanghaibin/p/4564930.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!