如何從 C# 中的執行緒獲取執行緒 ID?
執行緒被定義為程式的執行路徑。每個執行緒定義一個獨特的控制流。如果你的應用程式涉及複雜且耗時的操作,那麼設定不同的執行路徑或執行緒通常很有用,每個執行緒執行特定任務。
執行緒是輕量級程序。執行緒的一個常見使用示例是現代作業系統實現併發程式設計。使用執行緒可以節省 CPU 週期浪費並提高應用程式效率。
在 C# 中,System.Threading.Thread 類用於處理執行緒。它允許在多執行緒應用程式中建立和訪問單個執行緒。程序中要執行的第一個執行緒稱為主執行緒。
當 C# 程式開始執行時,主執行緒將自動建立。使用 Thread 類建立的執行緒稱為主執行緒的子執行緒。你可以使用 Thread 類的 CurrentThread 屬性訪問執行緒。
示例
class Program{ public static void Main(){ Thread thr; thr = Thread.CurrentThread; thr.Name = "Main thread"; Console.WriteLine("Name of current running " + "thread: {0}", Thread.CurrentThread.Name); Console.WriteLine("Id of current running " + "thread: {0}", Thread.CurrentThread.ManagedThreadId); Console.ReadLine(); } }
輸出
Name of current running thread: Main thread Id of current running thread: 1
廣告