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

Background และ Foreground Thread ใน C#

Thread คือเส้นทางการทำงานของโปรแกรม แต่ละ Thread มี Flow of control แยกกัน

Foreground Threads

  • ทำงานจนกว่าจะเสร็จ หรือถูก Abort
  • Application จะไม่ปิดจนกว่า Foreground threads ทุกตัวจะจบ
  • Default: Thread ที่สร้างด้วย new Thread() เป็น Foreground

Background Threads

  • จะถูก Terminate อัตโนมัติเมื่อ Foreground threads ทั้งหมดจบแล้ว
  • ไม่บล็อกการปิด Application
  • ตั้งค่าด้วย: thread.IsBackground = true;

ตัวอย่าง

// Foreground (Default)
Thread fg = new Thread(DoWork);
fg.Start();

// Background
Thread bg = new Thread(DoWork);
bg.IsBackground = true;
bg.Start();

// โปรแกรมจะปิดได้แม้ bg จะยังทำงานอยู่
// เพราะ fg เป็น Main thread (Foreground)

เมื่อไหร่ควรใช้ Background?

  • งานที่ไม่สำคัญ ถ้าหยุดกะทันหันก็ไม่เสียหาย (Logging, Cache cleanup, Auto-save)
  • Monitoring tasks, Polling

เมื่อไหร่ควรใช้ Foreground?

  • งานสำคัญที่ต้องเสร็จสิ้น (Save file, Transaction, Cleanup)
  • Main thread ของ Application