cpu รุ่นใหม่ๆ สามารถทำงานได้พร้อมๆ กันหลายๆ งานในเวลาเดียวกัน ทำไมจะไม่เขียนโปรแกรมให้ทำงานพร้อมๆ กันจะได้เสร็จไว้ๆ ละ
ตัวอย่าง c# Console App
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 | using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; namespace ConsoleApp1 { internal class Program { private static void Main( string [] args) { Dictionary< string , string > months = new Dictionary< string , string >() { { "01" , "January" }, { "02" , "February" }, { "03" , "March" }, { "04" , "April" }, { "05" , "May" }, { "06" , "June" }, { "07" , "July" }, { "08" , "August" }, { "09" , "September" }, { "10" , "October" }, { "11" , "November" }, { "12" , "December" }, }; var reultsts = new List<List< string >>(); Console.WriteLine( "Start Main" ); reultsts = RunAsync(months).Result; Console.WriteLine( "End Main get reultsts " + reultsts.Count() + " items" ); Console.ReadKey(); } public static async Task<List<List< string >>> RunAsync(Dictionary< string , string > months) { var tasks = new List<Task>(); var reultsts = new List<List< string >>(); Console.WriteLine( "Start RunAsync" ); foreach (KeyValuePair< string , string > item in months) { tasks.Add(Task.Run(() => { reultsts.Add(TaskRun(item.Key, item.Value).Result); })); } Task t = Task.WhenAll(tasks); try { t.Wait(); } catch { } Console.WriteLine( "End RunAsync" ); return reultsts; } public static async Task<List< string >> TaskRun( string key, string value) { Random random = new Random(); string message; int sleep; var results = new List< string >(); for ( int i = 0; i < 2; i++) { sleep = random.Next(1, 10) * 1000; System.Threading.Thread.Sleep(sleep); message = "TaskRun month " + key + " " + i + " " + sleep; results.Add(message); Console.WriteLine( "\t" + message); } return results; } } } |
จะเห็นว่าไม่ได้ทำงานตามลำดับเดือน แถมบางเดือนจะทำครั้งที่ 1 และครั้งที่ 2 ห่างกันมากด้วยซ้ำไปเพราะว่าการจำลองการทำงานด้วย sleep ที่สุ่มไว้ได้เวลาต่างกันมาก อันไหนทำเสร็จแล้วมันก็จะไปหยิบงานอื่นมาทำก่อนโดยไม่ต้องรอให้งานเสร็จตามลำดับ