Multithreading ใน C#
Multithreading ช่วยให้โปรแกรมทำงานหลายอย่างพร้อมกัน (Concurrency) โดยใช้คลาส System.Threading.Thread แต่ละ Thread เป็นเส้นทางการทำงานอิสระ
Thread หลัก (Main Thread)
- Thread แรกที่สร้างเมื่อโปรแกรมเริ่มรัน
- Thread อื่นๆ ที่สร้างขึ้น = Child Threads
ตัวอย่าง: สร้าง Thread แบบง่าย
using System;
using System.Threading;
namespace Demo
{
class Program
{
static void Main(string[] args)
{
Thread mainThread = Thread.CurrentThread;
mainThread.Name = "MainThread";
Console.WriteLine($"This is {mainThread.Name}");
Console.ReadKey();
}
}
}
ตัวอย่าง: สร้างและจัดการ Child Thread
using System;
using System.Threading;
namespace MultithreadingApplication
{
class ThreadCreationProgram
{
public static void CallToChildThread()
{
Console.WriteLine("Child thread starts");
int sleepFor = 5000;
Console.WriteLine($"Child Thread Paused for {sleepFor / 1000} seconds");
Thread.Sleep(sleepFor); // หยุด 5 วินาที
Console.WriteLine("Child thread resumes");
}
static void Main(string[] args)
{
ThreadStart childRef = new ThreadStart(CallToChildThread);
Console.WriteLine("In Main: Creating the Child thread");
Thread childThread = new Thread(childRef);
childThread.Start(); // เริ่ม Thread
Console.ReadKey();
}
}
}
ผลลัพธ์
In Main: Creating the Child thread
Child thread starts
Child Thread Paused for 5 seconds
Child thread resumes
Thread Lifecycle (วัฏจักรชีวิต)
- Unstarted - สร้าง Thread แต่อยู่ Start()
- Running/Ready - กำลังรันหรือรอ CPU
- WaitSleepJoin - Sleep, Wait, Join
- Suspended - ถูก Suspend (Deprecated)
- Stopped/Dead - จบการทำงานหรือ Abort
แนวทางสมัยใหม่ (Modern Alternatives)
- Task Parallel Library (TPL):
Task.Run(),Parallel.For,PLINQ - async/await: Asynchronous Programming แบบ Non-blocking
- ThreadPool: จัดการ Thread ให้อัตโนมัติ (QueueUserWorkItem)
- Channels, Dataflow: Producer-Consumer Patterns
⚠️ คำเตือน
หลีกเลี่ยงการใช้ Thread.Abort(), Thread.Suspend(), Thread.Resume() - Deprecated และอันตราย