Получение идентификатора потока от потока

notify() разбудит один поток, в то время как notifyAll() разбудит все. Насколько я знаю, что нет никакого второго плана. Но если Вы не уверены, что notify() сделает к Вашим потокам, используйте notifyAll(). Работы как очарование каждый раз.

304
задан jonsca 27 September 2012 в 01:40
поделиться

8 ответов

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.

422
ответ дан 23 November 2019 в 01:21
поделиться

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.

44
ответ дан 23 November 2019 в 01:21
поделиться

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

Это будут идентификаторы управляемых потоков. ManagedThreadId является членом Thread , поэтому вы можете получить идентификатор из любого объекта Thread . Это даст вам текущий ManagedThreadID :

Thread.CurrentThread.ManagedThreadId

Чтобы получить поток ОС по его идентификатору потока ОС (не ManagedThreadID) , вы можете попробовать немного linq.

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

Это похоже, что нет способа перечислить управляемые потоки и нет связи между ProcessThread и Thread, поэтому получить управляемый поток по его идентификатору непросто.

Подробнее об управляемом и неуправляемом потоках см. в этой статье MSDN

1116306].

76
ответ дан 23 November 2019 в 01:21
поделиться

To get the OS ID use:

AppDomain.GetCurrentThreadId()
31
ответ дан 23 November 2019 в 01:21
поделиться

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.

21
ответ дан 23 November 2019 в 01:21
поделиться

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;
     }
}
10
ответ дан 23 November 2019 в 01:21
поделиться

System.Threading.Thread.CurrentThread.Name

System.Threading.Thread.CurrentThread.ManagedThreadId
5
ответ дан 23 November 2019 в 01:21
поделиться

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.

5
ответ дан 23 November 2019 в 01:21
поделиться
Другие вопросы по тегам:

Похожие вопросы: