3
votes

I have a set of cpu consuming executions that each run in thread with low priority. These threads will be run in a Process (Like IIS) that have many other threads that I don't want to slow them. I want to calculate the cpu usage of all other threads and if its greater than 50% then i pause one of my threads, and if its smaller than 50% I resume a paused executions.

In pausing i save the state of execution in db and terminate its thread, and in resuming i start new thread.

What I Need is a function to return the cpu usage percentage of a thread.

private static void monitorRuns(object state)
{
  Process p = Process.GetCurrentProcess;
  double usage = 0;
  foreach(ProcessThread t in p.Threads)
  {
    if(!myThreadIds.Contains(t.Id)) // I have saved my own Thread Ids
    {
      usage += getUsingPercentage(t); // I need a method like getUsingPercentage
    }
  }

  if(usage > 50){
    pauseFirst(); // saves the state of first executions and terminates its threads
  }else{
    resumeFirst(); // start new thread that executes running using a state
  }
}

this function is called with a Timer:

Timer t = new Timer(monitorRuns,null,new TimeSpan(0,0,10),new TimeSpan(0,5,0));
1
A much better approach would be to set the ThreadPriority = Priority.Lowest; - Casperah
I think it would be much better to let the framework handle this. And setting the priority to a low value will give other threads priority. - Magnus
I have set ThreadPriority = Priority.Lowest;. is setting the priority enough? i dont want to slow down the server when its busy. - mrd abd

1 Answers

6
votes

To calculate process/thread CPU usage, you should get the processor time of a particular time frame of system/process/thread. And then you can calculate the CPU usage and don't forget to divide the value with the number of CPU cores.

ProcessWideThreadCpuUsage = (ThreadTimeDelta / CpuTimeDelta)
SystemWideThreadCpuUsage = (ThreadTimeDate / CpuTimeDelta) * ProcessCpuUsage

I found the example explains the approach. You can read it as a reference.