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?
In Python 3.3+, you can use threading. get_ident() function to obtain the thread ID of a thread.
Method One: PSIn ps command, "-T" option enables thread views. The following command list all threads created by a process with <pid>. The "SID" column represents thread IDs, and "CMD" column shows thread names.
In some threads implementations, the thread ID is a 4-byte integer that starts at 1 and increases by 1 every time a thread is created. This integer can be used in a non-portable fashion by an application.
Thread Id is a long positive integer that is created when the thread was created. During the entire lifecycle of a thread, the thread ID is unique and remains unchanged. It can be reused when the thread is terminated.
GetThreadId
returns the ID of a given native thread. There are ways to make it work with managed threads, I'm sure, all you need to find is the thread handle and pass it to that function.
GetCurrentThreadId
returns the ID of the current thread.
GetCurrentThreadId
has been deprecated as of .NET 2.0: the recommended way is the Thread.CurrentThread.ManagedThreadId
property.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With