"Michael Moreno" <mi*********************@free.fr> wrote in message
news:mn***********************@free.fr...
| Hello,
|
| I have a C# server which has 4 worker threads running all the time.
| When I let the server runs for several hours, for some reasons the CPU
| usage of the application will shoot to 100% and remain there.
| I would like to find out which thread(s) is/are the source of the
| problem.
|
| Would you have any idea on how to tackle the problem please?
|
| Thanks,
| Michael
|
| --
| Michael
| ----
|
http://michael.moreno.free.fr/
|
http://port.cogolin.free.fr/
|
|
Your best bet is to use the High-Performance counters through
System.Management and WMI.
Note that the thread usage is per OS thread, somehow you will need to find
the corresponding CLR thread (logical thread).
Note that in a hosted environmant like SQL Server 2005, this is not possible
as logical threads are mapped to OS fibers.
Here is a complete sample that illustrates how you can monitor process
thread usage.
using System;
using System.Management;
using System.Globalization;
using System.Threading;
class Program
{
public static void Main() {
string procName = "SomeApplication"; // app. to monitor, used in LIKE
predicate in select clause (wildcard)
TimerCallback timerDelegate = new TimerCallback (ManagedProcess);
// Monitor process who's name starts with procName
SelectQuery selectQuery = new SelectQuery("select * from
Win32_PerfRawData_PerfProc_Thread where name like " + "\"" + procName +
"%\"");
using(ManagementObjectSearcher searcher = new
ManagementObjectSearcher(selectQuery))
{
using(Timer timer = new Timer (timerDelegate, searcher, 0, 2000))
{
Console.ReadLine(); // suspend main thread.
}
}
}
private static void ManagedProcess(object obj)
{
ManagementObjectSearcher searcher = obj as ManagementObjectSearcher;
ManagementObjectCollection threads = searcher.Get();
ConsoleColor fc = Console.ForegroundColor;
Console.ForegroundColor=ConsoleColor.Red;
Console.WriteLine("{0,-20}{1,-10}{2,-20}{3,-10}{4,-10}{5} ",
"Name", "IDThread", "Elapsed msec.", "Pct Priv.", "Pct Proc.",
"Pct User");
Console.ForegroundColor=fc;
foreach(ManagementObject thread in threads)
{
// CPU usage since thread start time
ulong interval = (ulong)thread["TimeStamp_Object"] -
(ulong)thread["ElapsedTime"];
float pctPrivileged =
Convert.ToSingle((ulong)thread["PercentPrivilegedTime"]) /
Convert.ToSingle(interval);
float pctProcessor =
Convert.ToSingle((ulong)thread["PercentProcessorTime"]) /
Convert.ToSingle(interval);
float pctUser = Convert.ToSingle((ulong)thread["PercentUserTime"]) /
Convert.ToSingle(interval);
Console.WriteLine("{0,-20}{1,-10}{2,-20}{3,-10}{4,-10}{5} ",
thread["Name"].ToString(),
thread["IDThread"].ToString(),
(interval/10000).ToString(),
pctPrivileged.ToString("P"),
pctProcessor.ToString("P"),
pctUser.ToString("P"));
}
}
}
Willy.