0

I have a windows service that does long operations every X minutes using System.Timers.Timer. I need to kwnow if there is a way to figure out, in the next loop, if the previous execution is still running.
Is there a way to know how much CPU memory the previous thread using?

enfix
  • 6,680
  • 12
  • 55
  • 80
  • Add a global bool "IsRunning" that you set to true at the start and reset to false at the finish? – Hans Kesting Sep 09 '22 at 15:26
  • Is your intention to prevent overlapping executions? In case it is, you could take a look at this question: [Run async method regularly with specified interval](https://stackoverflow.com/questions/30462079/run-async-method-regularly-with-specified-interval). The techniques displayed there can be used also with synchronous methods. – Theodor Zoulias Sep 09 '22 at 15:29
  • You could create a temporary file at the beginning of the operation and delete it at the end. MongoDB creates a write.lock file in a similar manner. – Victor Wilson Sep 09 '22 at 16:28

1 Answers1

1

A simple solution would be to use a shared, volatile bool that is set in the start of the method, and reset at the end. Or use Interlocked.Increment/decrement of a shared counter to keep a running total of the number of threads in your method.

If you do not want invocations to overlap another, one solution would be to use a Threading.Timer, set the due-time you want and a infinite period. At the end of each event you call .Change to reset the due-time. Another way to do essentially the same thing would be a loop over Task.Delay:

while(!cancellationToke.IsCancellationRequested){
    // do work
   await Task.Delay(periodTime);
}

Your question about CPU/Memory does not make that much sense. A thread is either running, waiting to run, or blocked. And the only memory that can be directly attributed to the thread would be the stack for that thread, and that is usually quite small, and has a 1Mb limit by default if I'm remembering correctly. If you want to measure how much time a thread is in the running state, you need to do periodic sampling or instrument the scheduler.

JonasH
  • 28,608
  • 2
  • 10
  • 23
  • 1
    `/* do work */ await Task.Delay(periodTime);` is definitely not correct (does not implement a fixed period, it implements a fixed sleep time). Better is `var nextWake = Task.Delay(periodTime); /* do work */ await nextWake;` but that will still slowly accumulate clock skew. – Ben Voigt Sep 09 '22 at 19:03
  • @BenVoigt Well, yes, but it depends on the purpose. A fixed sleep time might be desired in some situations. – JonasH Sep 09 '22 at 19:09
  • 1
    And it those situations, you would not have any variable named "period" – Ben Voigt Sep 09 '22 at 22:03