zoukankan      html  css  js  c++  java
  • C# ado.net 使用task和await(四)

     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     }
  • 相关阅读:
    Java equals()和hashCode()重写总结
    常见ORM框架理解
    struts2的第一个小页面
    Java开发StringBuilder类
    “中软综合项目实训”——把学生当员工培养
    中软寻梦
    软件开发学习的5大技巧
    从学生心理入手
    IT技术人员的职业发展方向
    驱动创新 引领未来
  • 原文地址:https://www.cnblogs.com/farmer-y/p/6253233.html
Copyright © 2011-2022 走看看