C#中Task的用法
以下代码是对官方示例的修改:
using System; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; namespace ConsoleApp { class Program { static void Main(string[] args) { MakeBreakfast01(); MakeBreakfast02(); MakeBreakfast03(); Console.ReadLine(); } // 烤面包、煎蛋、煎肉一样一样做 public static void MakeBreakfast01() { Console.WriteLine("开始做早餐01"); Stopwatch watch = Stopwatch.StartNew(); Task.Run(async () => { await ToastBreadAsync(); await FryEggsAsync(); await FryBaconAsync(); }).Wait(); watch.Stop(); Console.WriteLine($"早餐01完成,耗时{watch.Elapsed.Seconds}秒"); } // 有一个面包机和一个锅,煎蛋、煎肉先后进行,烤面包同时进行 public static void MakeBreakfast02() { Console.WriteLine("开始做早餐02"); Stopwatch watch = Stopwatch.StartNew(); var taskToastBread = ToastBreadAsync(); var taskFryEggsAndBacon = Task.Run(async () => { await FryEggsAsync(); await FryBaconAsync(); }); Task.WaitAll(taskToastBread, taskFryEggsAndBacon); watch.Stop(); Console.WriteLine($"早餐02完成,耗时{watch.Elapsed.Seconds}秒"); } // 有一个面包机和两个锅,烤面包、煎蛋、煎肉三项同时进行 public static void MakeBreakfast03() { Console.WriteLine("开始做早餐03"); Stopwatch watch = Stopwatch.StartNew(); var taskToastBread = ToastBreadAsync(); var taskFryEggs = FryEggsAsync(); var taskFryBacon = FryBaconAsync(); Task.WaitAll(taskToastBread, taskFryEggs, taskFryBacon); watch.Stop(); Console.WriteLine($"早餐03完成,耗时{watch.Elapsed.Seconds}秒"); } // 煎蛋 public static async Task FryEggsAsync() { Console.WriteLine("开始煎蛋"); await Task.Delay(1000); Console.WriteLine("煎蛋完成"); } // 煎肉 public static async Task FryBaconAsync() { Console.WriteLine("开始煎肉"); await Task.Delay(1000); Console.WriteLine("煎肉完成"); } // 烤面包 public static async Task ToastBreadAsync() { Console.WriteLine("开始烤面包"); await Task.Delay(1000); Console.WriteLine("烤面包完成"); } } }
运行结果: