2

I have a console application which spins up multiple tasks at startup. Further each of these tasks have timers that do various async operations (db reads/writes).

I would like to calculate the CPU usage for each of these startup tasks (should include the sum of usages of the child tasks initiated by them) and log it periodically.

I already checked Get Thread Cpu Usage and How to get the CPU Usage in C#? But these seem to be either for a single thread or the entire process.

Would appreciate any help on this.

aknag
  • 63
  • 5
  • 2
    Could you include an example of a parent task, so that we can see how the timers are used to start the child asynchronous operations? – Theodor Zoulias Oct 27 '20 at 07:59
  • @TheodorZoulias, I have an interface with a method like `StartProcessing`. This interface is implemented by many classes. At the startup I get the instances of all these classes using DI. Then I'm using `Task.Run(() => someInstance.StartProcessing())` inside a `foreach`. Each of these classes have a `System.Timers.Timer` inside them which performs db (and more) operations on regular intervals. – aknag Oct 27 '20 at 08:08
  • I see. I was going to suggest a custom `TaskScheduler` for accumulating the duration of (hopefully) CPU-bound operations, but since you are scheduling the child tasks on the `ThreadPool` (this is what the `Task.Run` and `System.Timers.Timer` does), my suggestion is not applicable. – Theodor Zoulias Oct 27 '20 at 08:55
  • 1
    You could measure the time yourself with a System.Diagnostics.Stopwatch and then calculate the time of each operation using the whole process CPU time. – sneusse Oct 27 '20 at 11:50
  • @sneusse, that would miss information about fire and forget tasks. There are also multiple 3rd party calls / cloud services getting used. I was hoping for a way to avoid manual diagnostic code for each small operation. – aknag Oct 28 '20 at 05:57

0 Answers0