[c#] Getting the thread ID from a thread

In C# when debugging threads for example, you can see each thread's ID.

I couldn't find a way to get that same thread, programmatically. I could not even get the ID of the current thread (in the properties of the Thread.currentThread).

So, I wonder how does Visual Studio get the IDs of the threads, and is there a way to get the handle of the thread with id 2345, for example?

This question is related to c# .net multithreading

The answer is


You can use Thread.GetHashCode, which returns the managed thread ID. If you think about the purpose of GetHashCode, this makes good sense -- it needs to be a unique identifier (e.g. key in a dictionary) for the object (the thread).

The reference source for the Thread class is instructive here. (Granted, a particular .NET implementation may not be based on this source code, but for debugging purposes I'll take my chances.)

GetHashCode "provides this hash code for algorithms that need quick checks of object equality," so it is well-suited for checking Thread equality -- for example to assert that a particular method is executing on the thread you wanted it called from.


System.Threading.Thread.CurrentThread.Name

System.Threading.Thread.CurrentThread.ManagedThreadId

For those about to hack:

    public static int GetNativeThreadId(Thread thread)
    {
        var f = typeof(Thread).GetField("DONT_USE_InternalThread",
            BindingFlags.GetField | BindingFlags.NonPublic | BindingFlags.Instance);

        var pInternalThread = (IntPtr)f.GetValue(thread);
        var nativeId = Marshal.ReadInt32(pInternalThread, (IntPtr.Size == 8) ? 548 : 348); // found by analyzing the memory
        return nativeId;
    }

To get the OS ID use:

AppDomain.GetCurrentThreadId()

According to MSDN:

An operating-system ThreadId has no fixed relationship to a managed thread, because an unmanaged host can control the relationship between managed and unmanaged threads. Specifically, a sophisticated host can use the CLR Hosting API to schedule many managed threads against the same operating system thread, or to move a managed thread between different operating system threads.

So basically, the Thread object does not necessarily correspond to an OS thread - which is why it doesn't have the native ID exposed.


The offset under Windows 10 is 0x022C (x64-bit-Application) and 0x0160 (x32-bit-Application):

public static int GetNativeThreadId(Thread thread)
{
    var f = typeof(Thread).GetField("DONT_USE_InternalThread",
        BindingFlags.GetField | BindingFlags.NonPublic | BindingFlags.Instance);

    var pInternalThread = (IntPtr)f.GetValue(thread);
    var nativeId = Marshal.ReadInt32(pInternalThread, (IntPtr.Size == 8) ? 0x022C : 0x0160); // found by analyzing the memory
    return nativeId;
}

From managed code you have access to instances of the Thread type for each managed thread. Thread encapsulates the concept of an OS thread and as of the current CLR there's a one-to-one correspondance with managed threads and OS threads. However, this is an implementation detail, that may change in the future.

The ID displayed by Visual Studio is actually the OS thread ID. This is not the same as the managed thread ID as suggested by several replies.

The Thread type does include a private IntPtr member field called DONT_USE_InternalThread, which points to the underlying OS structure. However, as this is really an implementation detail it is not advisable to pursue this IMO. And the name sort of indicates that you shouldn't rely on this.


In C# when debugging threads for example, you can see each thread's ID.

This will be the Ids of the managed threads. ManagedThreadId is a member of Thread so you can get the Id from any Thread object. This will get you the current ManagedThreadID:

Thread.CurrentThread.ManagedThreadId

To get an OS thread by its OS thread ID (not ManagedThreadID), you can try a bit of linq.

int unmanagedId = 2345;
ProcessThread myThread = (from ProcessThread entry in Process.GetCurrentProcess().Threads
   where entry.Id == unmanagedId 
   select entry).First();

It seems there is no way to enumerate the managed threads and no relation between ProcessThread and Thread, so getting a managed thread by its Id is a tough one.

For more details on Managed vs Unmanaged threading, see this MSDN article.


To find the current thread Id use - `Thread.CurrentThread.ManagedThreadId'. But in this case you might need the current win32 thread id - use pInvoke to get it with this function:

[DllImport("Kernel32", EntryPoint = "GetCurrentThreadId", ExactSpelling = true)]
public static extern Int32 GetCurrentWin32ThreadId();

First you'll need to save the managed thread id and win32 thread id connection - use a dictionary that maps a win32 id to managed thread.

Then to find a thread by it's id iterate over the process's thread using Process.GetCurrentProcess().Threads and find the thread with that id:

foreach (ProcessThread thread in Process.GetCurrentProcess().Threads)
{
     var managedThread = win32ToManagedThread[thread.id];
     if((managedThread.ManagedThreadId == threadId)
     {
         return managedThread;
     }
}

You can use the deprecated AppDomain.GetCurrentThreadId to get the ID of the currently running thread. This method uses a PInvoke to the Win32 API method GetCurrentThreadID, and will return the Windows thread ID.

This method is marked as deprecated because the .NET Thread object does not correspond to a single Windows thread, and as such there is no stable ID which can be returned by Windows for a given .NET thread.

See configurator's answer for more reasons why this is the case.


Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to .net

You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to use Bootstrap 4 in ASP.NET Core No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization .net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible Update .NET web service to use TLS 1.2 EF Core add-migration Build Failed What is the difference between .NET Core and .NET Standard Class Library project types? Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=4.1.0.0' or one of its dependencies Nuget connection attempt failed "Unable to load the service index for source" Token based authentication in Web API without any user interface

Examples related to multithreading

How can compare-and-swap be used for a wait-free mutual exclusion for any shared data structure? Waiting until the task finishes What is the difference between Task.Run() and Task.Factory.StartNew() Why is setState in reactjs Async instead of Sync? What exactly is std::atomic? Calling async method on button click WAITING at sun.misc.Unsafe.park(Native Method) How to use background thread in swift? What is the use of static synchronized method in java? Locking pattern for proper use of .NET MemoryCache