如何在 C# 中獲取執行緒的當前上下文 ID?


要建立一個新執行緒。

Thread thread = Thread.CurrentThread;
thread.Name = "My new Thread”;

要獲取當前上下文 ID,請使用 ContextID 屬性。

Thread.CurrentContext.ContextID

讓我們看看完整程式碼 −

例項

 線上演示

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 = {0}", thread.Name);
         Console.WriteLine("current Context id: {0}", Thread.CurrentContext.ContextID);
         Console.ReadKey();
      }
   }
}

輸出

Thread Name = My new Thread
current Context id: 0

更新於: 2020 年 6 月 22 日

600 次瀏覽

開始您的職業生涯

透過完成課程獲取認證

開始
廣告
© . All rights reserved.