PerformanceCounter and ThreadID

  • Thread starter Thread starter Michael Moreno
  • Start date Start date
M

Michael Moreno

Good morning,

Here is the objective: monitoring the CPU usage of a given thread in my
own C# application.

Here is what I do:
- on a Form I put a PerformanceCounter
- I set e CategoryName = Thread
- I set the CounterName = % Processor time
- I set the Machine = . (local machine)

Then I am trying to set the InstanceName and it is where it all goes
wrong...
The InstanceName should be something like: MyAppName/5

And the problem is I do not know how to get the right number (5 or 6 or
7 ???).

I have tried with :
- AppDomain.GetCurrentThreadId()
- System.Threading.Thread.CurrentThread.GetHashCode

But neither of them is the number I need for the PerformanceCounter.

Can you help please?

Thanks.
 
CLR uses managed threads that do not have one to one mapping with OS
threads:

"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."

You *could* use Win32 API to get OS thread but it's not fully stable.

Laura
 
| Good morning,
|
| Here is the objective: monitoring the CPU usage of a given thread in my
| own C# application.
|
| Here is what I do:
| - on a Form I put a PerformanceCounter
| - I set e CategoryName = Thread
| - I set the CounterName = % Processor time
| - I set the Machine = . (local machine)
|
| Then I am trying to set the InstanceName and it is where it all goes
| wrong...
| The InstanceName should be something like: MyAppName/5
|
| And the problem is I do not know how to get the right number (5 or 6 or
| 7 ???).
|
| I have tried with :
| - AppDomain.GetCurrentThreadId()
| - System.Threading.Thread.CurrentThread.GetHashCode
|
| But neither of them is the number I need for the PerformanceCounter.
|
| Can you help please?
|
| Thanks.
|
| --
| Michael
| ----
| http://michael.moreno.free.fr/
| http://port.cogolin.free.fr/
|
|

'GetCurrentThreadId' returns the OS thread ID, which is the same as
perfcounter "ID Thread" counter, so you will have to compare this Perf
counter with the value returned by GetCurrentThreadId to find the right
thread.
Note that:
- GetCurrentThreadId is deprecated in V2 of the framework, you better
PInvoke Win32's GetCurrentThreadId API.
- you might consider using a separate process to monitor a process thread
consumption, monitoring your own process thread consumption is quite
intrusive and may disturb normal thread scheduling.
I posted a sample of the latter to your previous thread "Thread-CPU usage"
in this NG.

Willy.
 
Back
Top