如何在可视C#中获取线程ID [英] how to get thread ID in visual C#

查看:734
本文介绍了如何在可视C#中获取线程ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

HI FRINDS!
我想知道如何获取ID线程?(不是控制台模式,视觉模式)+ _ +谢谢您

HI FRINDS!
I want to know how can i get the ID thread ?(not the console mode,the visual mode) +_+ thank you

推荐答案

Thread.CurrentThread.ManagedThreadId应该可以工作.


调用以获取当前的托管线程ID.

Call to get the current managed thread id.

int threadId = System.Threading.Thread.CurrentThread.ManagedThreadId;



如果您使用的是所有线程所在的当前进程ID.



If you what the current process id where all your threads lives.

int processId = System.Diagnostics.GetCurrentProcess().Id;


您已经被回答了.但是这里的一些信息可能并不明显. ManagedThreadId 返回与托管线程关联的唯一ID.这不是基础本机线程的ID.因此,您不能将其传递给任何需要threadId参数的本机API.

为此,您需要从正在运行的线程P/调用GetCurrentThreadId .不过要当心.缓存此值是有风险的,因为在某些情况下,CLR可能会将托管线程移动到其他本机线程中(这是极为罕见的,但并非不可能).因此,您需要在使用它之前先调用它,以便您可以安全使用它.如果在同一方法中使用它,则CLR无法在该方法调用期间移动托管线程.

人们使用的另一种技巧是有意将本机堆栈框架引入调用堆栈.这将防止CLR将托管线程移动到新的本机线程中,因为这将完全破坏调用堆栈.不过,我看不出有任何真正好的理由采取这种极端措施.
You''ve already been answered. But here''s some info that may not be obvious. ManagedThreadId returns the unique ID associated with the managed thread. This is not the ID of the underlying native thread. So you cannot pass this to any native API that requires a threadId parameter.

For that you need to P/Invoke GetCurrentThreadId from the running thread. Beware though. It''s risky to cache this value because under certain circumstances the CLR may move a managed thread into a different native thread (it''s extremely rare, but is not an impossible scenario). So you need to call this prior to using it so you know you can use it safely. If you use it within the same method, the CLR cannot move the managed thread for the duration of that method call.

Another hack people use is to intentionally introduce a native stack frame into the call stack. This will prevent the CLR from moving the managed thread into a new native thread since that will completely wreck the call stack. I can''t see any really good reasons to resort to such extreme measures though.


这篇关于如何在可视C#中获取线程ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆