1. 程式人生 > 其它 >C#簡單易懂非同步實現程式碼例項

C#簡單易懂非同步實現程式碼例項

程式碼:來源

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Diagnostics;
 4 using System.Linq;
 5 using System.Runtime.InteropServices;
 6 using System.Text;
 7 using System.Threading;
 8 using System.Threading.Tasks;
 9 using Test_Roslyn.JSON_MODEL;
10 
11 namespace C_Sharp_Test
12
{ 13 class Program 14 { 15 16 static async Task Main(string[] args) 17 { 18 Console.WriteLine("Main非同步演示開始~~~~~"); 19 Stopwatch stopwatch = Stopwatch.StartNew(); 20 List<Task> tasks = new List<Task> 21 { 22 Bash(),//
洗澡 23 }; 24 tasks.Add(BreakFast());//吃早餐 25 tasks.Add(WashClothes());//洗衣服 26 tasks.Add(WriteArticle());//寫文章 27 tasks.Add(WritingCode());//寫程式碼 28 await Task.WhenAll(tasks); 29 Console.WriteLine("Main非同步演示結束~~~~~共用時{0}秒!", stopwatch.ElapsedMilliseconds / 1000
); 30 Console.ReadKey(); 31 } 32 33 private static async Task Bash() 34 { 35 Console.WriteLine("洗澡開始~~~~~"); 36 await Task.Delay(1 * 1000);//模擬過程 37 Console.WriteLine("洗澡結束~~~~~"); 38 } 39 40 private static async Task BreakFast() 41 { 42 Console.WriteLine("吃早餐開始~~~~~"); 43 await Task.Delay(1 * 1000);//模擬過程 44 Console.WriteLine("吃早餐結束~~~~~"); 45 } 46 47 private static async Task WashClothes() 48 { 49 Console.WriteLine("洗衣服開始~~~~~"); 50 await Task.Delay(6 * 1000);//模擬過程 51 Console.WriteLine("洗衣服結束~~~~~"); 52 53 } 54 55 private static async Task WriteArticle() 56 { 57 Console.WriteLine("寫文章開始~~~~~"); 58 await Task.Delay(20 * 1000);//模擬過程 59 Console.WriteLine("寫文章結束~~~~~"); 60 } 61 62 private static async Task WritingCode() 63 { 64 Console.WriteLine("寫程式碼開始~~~~~"); 65 await Task.Delay(12 * 1000);//模擬過程 66 Console.WriteLine("寫程式碼結束~~~~~"); 67 } 68 } 69 }

例項: