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

Tìm Context ID của luồng hiện tại trong C#

Thread.CurrentContext.ContextID trả về ID của ngữ cảnh thực thi (execution context) hiện tại. Context quản lý các thuộc tính như bảo mật, đồng bộ hóa, call context.

Ví dụ minh họa

using System;
using System.Threading;

class Program
{
    static void Main()
    {
        Thread currentThread = Thread.CurrentThread;
        currentThread.Name = "Luồng chính";
        
        Console.WriteLine($"Tên luồng: {currentThread.Name}");
        Console.WriteLine($"Context ID: {Thread.CurrentContext.ContextID}");
        Console.WriteLine($"Thread ID (Managed): {currentThread.ManagedThreadId}");
        Console.WriteLine($"Thread ID (OS): {GetCurrentThreadId()}");
        
        // Tạo luồng mới
        Thread newThread = new Thread(() => 
        {
            Console.WriteLine($"\nLuồng mới - Context ID: {Thread.CurrentContext.ContextID}");
            Console.WriteLine($"Managed Thread ID: {Thread.CurrentThread.ManagedThreadId}");
        });
        newThread.Start();
        newThread.Join();
    }
    
    // P/Invoke để lấy OS thread ID (Windows)
    [System.Runtime.InteropServices.DllImport("kernel32.dll")]
    static extern int GetCurrentThreadId();
}

Kết quả đầu ra (ví dụ)

Tên luồng: Luồng chính
Context ID: 0
Thread ID (Managed): 1
Thread ID (OS): 12344

Luồng mới - Context ID: 0
Managed Thread ID: 4

Giải thích: Context ID thường là 0 trong ứng dụng đơn giản. Context khác nhau khi dùng SynchronizationAttribute, COM interop, hoặc ContextBoundObject.