码迷,mamicode.com
首页 > Windows程序 > 详细

C# ado.net 使用task和await(四)

时间:2017-01-05 18:02:44      阅读:239      评论:0      收藏:0      [点我收藏+]

标签:running   order   scalar   man   turn   oid   watch   pen   ogr   

 1     class Program
 2     {
 3         private static string constr = "server=.;database=northwnd;integrated security=sspi";
 4         static void Main(string[] args)
 5         {
 6             Console.WriteLine("Running tasks...");
 7 
 8             MethodTimer.TimeMethod(() =>
 9             {
10                 var t1 = GetEmployeeCount();
11                 var t2 = GetOrderCount();
12 
13                 Task.WaitAll(t1, t2);
14                 Console.WriteLine("Number of employes: {0}, Number of orders: {1}", t1.Result, t2.Result);
15             }, 1, "Getting data took {1}ms");
16         }
17         public static async Task GetEandO()
18         {
19             int e =await GetEmployeeCount();
20             int o = await GetOrderCount();
21 
22             Console.WriteLine("Number of employes: {0}, Number of orders: {1}", e, o);
23         }
24 
25         public async static Task<int> GetEmployeeCount()
26         {
27             using (SqlConnection con=new SqlConnection(constr) )
28             {
29                 SqlCommand cmd = new SqlCommand("WaitFor Delay 0:0:02;select count(*) from employees", con);
30                 con.Open();
31                 return await cmd.ExecuteScalarAsync().ContinueWith(t => Convert.ToInt32(t.Result));
32             }
33         }
34         public async static Task<int> GetOrderCount()
35         {
36             using (SqlConnection conn = new SqlConnection(constr))
37             {
38                 SqlCommand cmd = new SqlCommand("WAITFOR DELAY 0:0:02;select count(*) from orders", conn);
39                 conn.Open();
40 
41                 return await cmd.ExecuteScalarAsync().ContinueWith(t => Convert.ToInt32(t.Result));
42             }
43         } 
44     }
45     public class MethodTimer
46     {
47         public static void TimeMethod(Action method, int iterations, string message)
48         {
49             Stopwatch sw = Stopwatch.StartNew();
50 
51             for (int i = 0; i < iterations; i++)
52                 method();
53 
54             sw.Stop();
55 
56             Console.WriteLine(message, iterations, sw.ElapsedMilliseconds);
57         }
58     }

 

C# ado.net 使用task和await(四)

标签:running   order   scalar   man   turn   oid   watch   pen   ogr   

原文地址:http://www.cnblogs.com/farmer-y/p/6253233.html

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