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 }
时间: 2024-10-12 21:41:02