Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Lấy trạng thái Thread hiện tại trong C#

Dùng Thread.CurrentThread và property IsAlive.

Thread t = Thread.CurrentThread;
t.Name = "Our Thread";
Console.WriteLine("Trạng thái: {0}", t.IsAlive);

Ví dụ

using System;
using System.Threading;

namespace Demo
{
    class MyClass
    {
        static void Main(string[] args)
        {
            Thread t = Thread.CurrentThread;
            t.Name = "Our Thread";
            Console.WriteLine("Trạng thái = {0}", t.IsAlive);
            Console.ReadKey();
        }
    }
}

Kết quả

Trạng thái = True

Các property hữu ích:

  • IsAlive: thread đang chạy (chưa kết thúc)
  • IsBackground: background thread?
  • ThreadState: enum chi tiết (Running, WaitSleepJoin, Suspended, Stopped...)
  • ManagedThreadId: ID duy nhất
  • Name: tên debug
  • Priority: độ ưu tiên

Lưu ý: IsAlive = true cho đến khi thread kết thúc (return từ method, exception không catch, Abort).