AppDomain.GetCurrentThreadID vs Thread.ManagedThreadID for Windows API calls?

前端 未结 5 1618
独厮守ぢ
独厮守ぢ 2021-01-11 10:23

I\'m trying to create a hook to monitor the current position of the mouse cursor. Nothing important, I just need to count some pixels during interface design and wanted to l

相关标签:
5条回答
  • 2021-01-11 10:30
    var thread = Process.GetCurrentProcess().Threads.OfType<ProcessThread>().
        SingleOrDefault(x => x.ThreadState == ThreadState.Running);
    
    if (thread != null)
    {
        // do stuff here
    }
    
    0 讨论(0)
  • 2021-01-11 10:31

    It is not possible to use ManagedThreadId in this context. This is a completely managed concept and has no real representation in the native world. Hence it doesn't make any sense to the API's you're passing it to.

    The reason ManagedThreadId exists is because there is not necessarily a 1-1 mapping between a native and managed thread. The CLR is free to use multiple native threads to run a single managed thread as long as the native thread is compatible with the one it's replacing. It cannot for instance, be in a different COM apartment.

    In some ways you're a bit stuck here. AFAIK, there is no way to 100% guarantee that you will have the same native thread for a given managed thread. You can achieve a very high level of guarantee though if you are for instance running a WinForms or WPF application and the call to native code occurs on the UI thread. The reason being that both of these UI frameworks live in STA apartments which makes it very hard (if even possible) for the CLR to switch out from under you.

    Short Version: If you're in a WinForms or WPF application and running this on the UI thread, you can assume a reasonable level of stability for this identifier.

    0 讨论(0)
  • 2021-01-11 10:45

    use:

    [DllImport("kernel32.dll")] static extern uint GetCurrentThreadId();

    0 讨论(0)
  • 2021-01-11 10:46

    You could use:

    using System.Diagnostics;
    Process.GetCurrentProcess().Threads[0].Id
    

    instead of

    AppDomain.GetCurrentThreadId()

    The problem is only to find the correct number of the thread if you have more threads than the main thread 0 running.

    0 讨论(0)
  • 2021-01-11 10:50

    For future readers: There are also System.Threading.Thread.BeginThreadAffinity() / EndThreadAffinity() functions that purportedly stop the VM from switching between different physical threads. I don't believe these guarantee stability, but I think they're more likely to be stable.

    0 讨论(0)
提交回复
热议问题