Giới thiệu
Thuộc tính tĩnh Thread.CurrentThread trong namespace System.Threading trả về đối tượng Thread đại diện cho luồng (thread) đang thực thi code hiện tại. Cho phép truy cập thông tin luồng: Name, ManagedThreadId, ThreadState, Priority, IsThreadPoolThread, v.v.
Cú pháp
public static Thread CurrentThread { get; }
Ví dụ 1
using System;
using System.Threading;
public class Demo
{
public static void Main()
{
Thread thread = new Thread(new ThreadStart(Demo1));
ThreadPool.QueueUserWorkItem(new WaitCallback(Demo2));
thread = Thread.CurrentThread; // Lấy luồng chính (main thread)
thread.Name = "Demo Thread";
Console.WriteLine("Luồng đang chạy = " + thread.Name);
Console.WriteLine("Trạng thái luồng = " + thread.ThreadState);
Console.WriteLine("ManagedThreadId = " + thread.ManagedThreadId);
}
public static void Demo1()
{
Thread.Sleep(2000);
}
public static void Demo2(object stateInfo)
{
Console.WriteLine("Luồng thuộc thread pool? = " + Thread.CurrentThread.IsThreadPoolThread);
}
}
Kết quả
Luồng đang chạy = Demo Thread Trạng thái luồng = Running ManagedThreadId = 20 Luồng thuộc thread pool? = True
Ví dụ 2
using System;
using System.Threading;
public class Demo
{
public static void Main()
{
Thread thread = new Thread(new ThreadStart(Demo1));
ThreadPool.QueueUserWorkItem(new WaitCallback(Demo2));
thread = Thread.CurrentThread;
thread.Name = "Demo Thread";
Console.WriteLine("Luồng đang chạy = " + thread.Name);
Console.WriteLine("Trạng thái luồng = " + thread.ThreadState);
Console.WriteLine("ManagedThreadId = " + thread.ManagedThreadId);
Console.WriteLine("Thread Id: {0}", Thread.CurrentThread.ManagedThreadId);
}
public static void Demo1()
{
Thread.Sleep(2000);
}
public static void Demo2(object stateInfo)
{
Console.WriteLine("Luồng thuộc thread pool? = " + Thread.CurrentThread.IsThreadPoolThread);
}
}
Kết quả
Luồng đang chạy = Demo Thread Trạng thái luồng = Running ManagedThreadId = 29 Thread Id: 29 Luồng thuộc thread pool? = True
Các thuộc tính hữu ích của Thread
| Thuộc tính | Mô tả |
|---|---|
ManagedThreadId |
ID duy nhất do CLR gán cho luồng quản lý. |
Name |
Tên luồng (hữu ích cho debug). |
ThreadState |
Trạng thái: Running, WaitSleepJoin, Suspended, Stopped, v.v. |
Priority |
Độ ưu tiên: Lowest, BelowNormal, Normal, AboveNormal, Highest. |
IsThreadPoolThread |
True nếu luồng thuộc thread pool. |
IsBackground |
True nếu luồng nền (không giữ tiến trình sống). |
CurrentCulture / CurrentUICulture |
Văn hóa cho format/parse và resource. |
Lưu ý quan trọng
Thread.CurrentThreadluôn trả về luồng đang chạy code đó (context-dependent).- Trong async/await, luồng có thể thay đổi sau await (trừ khi dùng
ConfigureAwait(false)). - Không nên dùng
Thread.Abort(),Suspend(),Resume()(deprecated, không an toàn). - Ưu tiên dùng
Task,async/await,Parallel,PLINQthay cho thao tác Thread trực tiếp.