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

หา Current Context ID ของ Thread ใน C#

ภาพรวม

ใช้ Thread.CurrentContext.ContextID เพื่อดู Context ID ของเธรดปัจจุบัน Context ใช้สำหรับการจัดการการเข้าถึงข้าม AppDomain หรือ Context-bound objects

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


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 Name = {thread.Name}");
            Console.WriteLine($"Current Context ID: {Thread.CurrentContext.ContextID}");
            Console.WriteLine($"Thread ID: {thread.ManagedThreadId}");
            Console.WriteLine($"Is ThreadPool Thread: {thread.IsThreadPoolThread}");
            Console.WriteLine($"Is Background: {thread.IsBackground}");

            Console.ReadKey();
        }
    }
}

ผลลัพธ์


Thread Name = My new Thread
Current Context ID: 0
Thread ID: 1
Is ThreadPool Thread: False
Is Background: False

คำอธิบาย

  • Context ID: รหัสของ Context ปัจจุบัน (ปกติเป็น 0 สำหรับ default context)
  • ManagedThreadId: ID ที่ .NET มอบให้เธรด (unique ตลอด process)
  • Context ใช้กับ ContextBoundObject สำหรับ interception (AOP, remoting, synchronization)
  • ในโปรแกรมทั่วไป Context ID จะเป็น 0 เสมอ

ข้อมูลเพิ่มเติมของ Thread


Thread t = Thread.CurrentThread;
Console.WriteLine($"Priority: {t.Priority}");
Console.WriteLine($"Culture: {t.CurrentCulture.Name}");
Console.WriteLine($"UICulture: {t.CurrentUICulture.Name}");