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

โปรแกรม C# ตรวจสอบสถานะ Current Thread

ใช้ property IsAlive ของคลาส Thread ตรวจสอบว่าเธรดยังทำงานอยู่หรือไม่

ตัวอย่างโค้ดเต็ม

using System;
using System.Threading;
namespace Demo {
    class MyClass {
        static void Main(string[] args) {
            Thread thread = Thread.CurrentThread;
            thread.Name = "My New Thread";
            Console.WriteLine("Thread Status = {0}", thread.IsAlive);
            Console.ReadKey();
        }
    }
}

ผลลัพธ์

Thread Status = True

คำอธิบาย: Thread.CurrentThread คือเธรดที่กำลังรันโค้ดอยู่ จึงเป็น Alive เสมอ (True) จนกว่าจะจบการทำงาน

การใช้งานจริง: มักใช้กับเธรดอื่น (worker thread) เพื่อเช็คว่าเสร็จสิ้นงานหรือยัง

Thread worker = new Thread(DoWork);
worker.Start();
// ... ทำอย่างอื่น ...
if (worker.IsAlive) {
    // ยังทำงานอยู่
}