1

I have a C# program that needs to dispatch a thread every X minutes, but only if the previously dispatched thread (from X minutes) ago is not currently still running.

A plain old Timer alone will not work (because it dispatches an event every X minutes regardless or whether or not the previously dispatched process has finished yet).

The process that's going to get dispatched varies wildly in the time it takes to perform it's task - sometimes it might take a second, sometimes it might take several hours. I don't want to start the process again if it's still processing from the last time it was started.

Can anyone provide some working C# sample code?

Neel
  • 11,625
  • 3
  • 43
  • 61
  • possible duplicate of [How to let Timer skip tick if the previous thread is still busy](http://stackoverflow.com/questions/3424907/how-to-let-timer-skip-tick-if-the-previous-thread-is-still-busy) – H H Jan 31 '13 at 09:44
  • This has been asked & answered many times here. For various Timer classes. – H H Jan 31 '13 at 09:46

3 Answers3

1

you can just check if the thread is alive before you activate another thread.
do this using Thread.IsAlive.

Dor Cohen
  • 16,769
  • 23
  • 93
  • 161
1

I think a timer could work in this scenario. When the timer elapses it tries to obtain a lock on a synchronisation object. If it succeeds then it proceeds with it's work. If it fails to obtain the lock it knows the last thread has not finished so returns.

If you are using .Net 4.0 or above you could use Monitor.TryEnter(object, bool).

bool acquiredLock = false;
try
{
    Monitor.TryEnter(lockObject, ref acquiredLock);
    if (acquiredLock)
    {
        //do your work here
    }
}
finally
{
    if (acquiredLock)
    {
        Monitor.Exit(lockObject);
    }
}
Daniel Kelley
  • 7,579
  • 6
  • 42
  • 50
1

Use a while(True) loop in the thread. Record the start time at the top of the loop, perform the task, get the time again, calculate how much time has elaspsed and compare withv the start time. If this is less than X, convert the difference into ms and Sleep() for it.

No timer, no continual thread create, no synchro, no polling, no chance at all that two task instances will ever run concurrently.

Martin James
  • 24,453
  • 3
  • 36
  • 60