Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

มัลติเธรดดิง (Multithreading) ใน C#

มัลติเธรดดิง (Multithreading) ใน C#

มัลติเธรดดิงคือการรันโค้ดหลายส่วนพร้อมกัน (concurrently) ในโปรแกรมเดียวกัน แต่ละเธรดมีเส้นทางการทำงาน (execution path) ของตัวเอง ใน C# ใช้คลาส System.Threading.Thread สำหรับจัดการเธรด

เธรดหลัก (Main Thread)

เธรดแรกที่รันเมื่อโปรแกรมเริ่มต้น ทุกโปรแกรม C# มีเธรดหลักอย่างน้อย 1 ตัว

สถานะของเธรด (เหมือนกับ Thread Life Cycle)

  • Unstarted: สร้างแล้วแต่ยังไม่ Start()
  • Ready/Running: พร้อมรัน/กำลังรัน
  • Not Runnable: Sleep, Wait, Join, I/O Block
  • Dead: จบการทำงานหรือ Abort

ตัวอย่าง: สร้างเธรดใหม่

using System;
using System.Threading;

namespace Demo
{
    class Program
    {
        static void Main(string[] args)
        {
            // สร้างเธรดใหม่โดยระบุเมธอดที่จะรัน
            Thread workerThread = new Thread(DoWork);
            workerThread.Name = "WorkerThread";
            
            Console.WriteLine("Main thread: เริ่มสร้าง worker thread");
            workerThread.Start(); // เริ่มรันเธรด
            
            // Main thread ทำงานต่อไปพร้อมกัน
            for (int i = 0; i < 3; i++)
            {
                Console.WriteLine($"Main thread ทำงาน: {i}");
                Thread.Sleep(500);
            }
            
            workerThread.Join(); // รอ worker thread จบ
            Console.WriteLine("Main thread: worker thread จบแล้ว");
            Console.ReadKey();
        }

        static void DoWork()
        {
            for (int i = 0; i < 5; i++)
            {
                Console.WriteLine($"Worker thread ทำงาน: {i}");
                Thread.Sleep(300);
            }
        }
    }
}

ผลลัพธ์ตัวอย่าง (ลำดับอาจสลับกันได้)

Main thread: เริ่มสร้าง worker thread
Main thread ทำงาน: 0
Worker thread ทำงาน: 0
Worker thread ทำงาน: 1
Main thread ทำงาน: 1
Worker thread ทำงาน: 2
Main thread ทำงาน: 2
Worker thread ทำงาน: 3
Worker thread ทำงาน: 4
Main thread: worker thread จบแล้ว

เมธอดสำคัญของ Thread

เมธอดคำอธิบาย
Start()เริ่มรันเธรด
Sleep(ms)หยุดเธรดปัจจุบันเป็นมิลลิวินาที
Join()รอเธรดอื่นจบการทำงาน
Abort()ยกเลิกเธรด (Deprecated, ไม่แนะนำ)
Interrupt()ขัดจังหวะเธรดที่อยู่ใน WaitSleepJoin

แนวทางปัจจุบัน: Task และ async/await

ใน .NET Core/.NET 5+ ควรใช้ Task.Run(), async/await, Parallel, PLINQ แทนการใช้ Thread โดยตรง เพื่อ:

  • จัดการ Thread Pool อัตโนมัติ
  • หลีกเลี่ยง deadlock และ race condition
  • โค้ดอ่านง่ายและบำรุงรักษาง่าย
// แนวทางสมัยใหม่
await Task.Run(() => DoHeavyWork());
// หรือ
Task.Run(() => DoHeavyWork());