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?
CodePudding user response:
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.