C# - How to get the current thread id

Windows 95 was the first Windows operating system to support threads. Threads are created, managed, and scheduled by Windows.

The following terms are equivalent:
  • OS thread
  • Native thread
  • Unmanaged thread (in .NET paralance)

An OS thread that executes under the CLR becomes a Managed thread with a Managed thread id. Managed threads are represented by the .NET type System.Threading.Thread.

There is a 1-1 mapping between OS threads and CLR threads.

An example:


  class Program
  {
      [DllImport("kernel32.dll")]
      static extern int GetCurrentThreadId();
 
      static void Main(string[] args)
      {
          // managed tid
          var managed = System.Threading.Thread.CurrentThread.ManagedThreadId;
 
          // os tid
          var os1 = AppDomain.GetCurrentThreadId(); // deprecated according to ms, but if you need the os thread id, this IS the call to use
          var os2 = GetCurrentThreadId();
          var os3 = System.Diagnostics.Process.GetCurrentProcess().Threads[0].Id;
 
          Console.WriteLine("tid managed  = " + managed);
          Console.WriteLine("");
          Console.WriteLine("tid os1      = " + os1);
          Console.WriteLine("tid os2      = " + os2);
          Console.WriteLine("tid os3      = " + os3);
      }
  }
  

Program output:


  tid managed  = 1
  
  tid os1      = 8028
  tid os2      = 8028
  tid os3      = 8028
  

Ads by Google


Ask a question, send a comment, or report a problem - click here to contact me.

© Richard McGrath