c# - How do I get the _real_ thread id in a CLR "friendly" way? -
as exercise writing code display o/s processes , o/s threads within process (like sysinternals process explorer does).
i found .net's managedthreadid(s) not o/s thread ids. after bit of reading came across appdomain.getcurrentthreadid(). unfortunately, function marked "obsolete" (which mean "not available" in future). 1 solution found use interopservices directly call win32 getcurrentthreadid. fine but, feels counter .net philosophy.
my question is: there clr "friendly" way of obtaining real id of current thread ?
for reference, here snippet of code showing i've tried far. // 1 , // 2 display correct thread id, // 3 , // 4 attempts obtain same info in clr friendly way (but don't work.)
thank help,
john.
[dllimport("kernel32.dll")] static extern int getcurrentthreadid(); static void main(string[] args) { // appdomain.getcurrentthreadid() "obsolete" int threadid1 = appdomain.getcurrentthreadid(); // 1 // not ".net" way of doing things int threadid2 = getcurrentthreadid(); // 2 // "no joy" attempts same results got above int threadid3 = process.getcurrentprocess().threads[0].id; // 3 int threadid4 = thread.currentthread.managedthreadid; // 4 console.writeline("threadid1: {0}, threadid2: {1}, threadid3: {2}, " + "threadid4: {3}", threadid1, threadid2, threadid3, threadid4); }
pinvoking getcurrentthreadid best bet , give correct information.
however must warn you, there reasons why clr doesn't provide information: it's useless value managed code. it's legal clr perspective single managed thread backed several different native threads during it's lifetime. means result of getcurrentthreadid can (and will) change throughout course of thread's lifetime.
in many applications not observable phenomenon. in ui application won't happen because it's typically backed sta thread harder (usually illegal) swap out due com interop issues. many developers blissfully ignorant of this. it's easy swap out mta threads under hood typically execution context of background thread.
Comments
Post a Comment