Tag Archive threading

Byphunsanit

c#: แบ่งงานช่วยกันรุมให้เสร็จโดย Tasks

cpu รุ่นใหม่ๆ สามารถทำงานได้พร้อมๆ กันหลายๆ งานในเวลาเดียวกัน ทำไมจะไม่เขียนโปรแกรมให้ทำงานพร้อมๆ กันจะได้เสร็จไว้ๆ ละ

ตัวอย่าง c# Console App

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 ที่สุ่มไว้ได้เวลาต่างกันมาก อันไหนทำเสร็จแล้วมันก็จะไปหยิบงานอื่นมาทำก่อนโดยไม่ต้องรอให้งานเสร็จตามลำดับ