3

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));
mrd abd
  • 828
  • 10
  • 19
  • 2
    A much better approach would be to set the ThreadPriority = Priority.Lowest; – Casperah Jun 13 '14 at 08:42
  • 2
    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 Jun 13 '14 at 08:44
  • I have set `ThreadPriority = Priority.Lowest;`. is setting the priority enough? i dont want to slow down the server when its busy. – mrd abd Jun 13 '14 at 08:48

1 Answers1

7

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.

stanleyxu2005
  • 8,081
  • 14
  • 59
  • 94
  • @mrdabd Okay, there are similar apis for c#. Check my updated answer. – stanleyxu2005 Jun 13 '14 at 09:04
  • 1
    I download example, not working. it has an exception (`System.ComponentModel.Win32Exception` Message=`Access is denied`) – mrd abd Jun 13 '14 at 09:09
  • Your code is bound to get access denied if you don't assign the required permissions. This is not an issue with the answer provided, although it would be nice if someone figured out what permission is required and edit the answer to include this. – bikeman868 Aug 06 '19 at 14:30