70

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?

Keith Palmer Jr.
  • 27,666
  • 16
  • 68
  • 105
  • 1
    Which timer class? `System.Timers.Timer`, `Windows.Forms.Timer`, `System.Threading.Timer`? – Peter Ritchie Sep 24 '12 at 18:05
  • 2
    Matt Johnson's answer is what you want, I don't understand what you don't like about his solution...simple and to the point. – Mike Marynowski Jan 26 '13 at 22:36
  • Someone else did something similiar using the TPL, heres the link: http://stackoverflow.com/questions/4890915/is-there-a-task-based-replacement-for-system-threading-timer – Keith Jan 28 '13 at 21:44
  • 2
    @KeithPalmer If the timer is set to fire each 5 minutes. It fires a first time at t=0, the process associated to the event takes 7 min. So, it ends at t=7 min. When do you want the timer to fire the next time? At t=7 min, at t=10 min or at t=7+5=12 min? – Cédric Bignon Jan 30 '13 at 01:11
  • @KeithPalmer Could you answer to my question above please. It will help us to give you a correct solution. – Cédric Bignon Jan 30 '13 at 17:13
  • @Cedric Bignon - I don't really care, as long as it doesn't run while the previous event is still running, and as long as they can't "stack" on top of each other (e.g. if the first session takes 15 minutes, it shouldn't then immediately run both of the missed sessions immediately after finishing the first). – Keith Palmer Jr. Jan 30 '13 at 18:48

16 Answers16

62

In my opinion the way to go in this situation is to use System.ComponentModel.BackgroundWorker class and then simply check its IsBusy property each time you want to dispatch (or not) the new thread. The code is pretty simple; here's an example:

class MyClass
{    
    private BackgroundWorker worker;

    public MyClass()
    {
        worker = new BackgroundWorker();
        worker.DoWork += worker_DoWork;
        Timer timer = new Timer(1000);
        timer.Elapsed += timer_Elapsed;
        timer.Start();
    }

    void timer_Elapsed(object sender, ElapsedEventArgs e)
    {
        if(!worker.IsBusy)
            worker.RunWorkerAsync();
    }

    void worker_DoWork(object sender, DoWorkEventArgs e)
    {
        //whatever You want the background thread to do...
    }
}

In this example I used System.Timers.Timer, but I believe it should also work with other timers. The BackgroundWorker class also supports progress reporting and cancellation, and uses event-driven model of communication with the dispatching thread, so you don't have to worry about volatile variables and the like...

EDIT

Here's more elaborate example including cancelling and progress reporting:

class MyClass
{    
    private BackgroundWorker worker;

    public MyClass()
    {
        worker = new BackgroundWorker()
        {
            WorkerSupportsCancellation = true,
            WorkerReportsProgress = true
        };
        worker.DoWork += worker_DoWork;
        worker.ProgressChanged += worker_ProgressChanged;
        worker.RunWorkerCompleted += worker_RunWorkerCompleted;

        Timer timer = new Timer(1000);
        timer.Elapsed += timer_Elapsed;
        timer.Start();
    }

    void timer_Elapsed(object sender, ElapsedEventArgs e)
    {
        if(!worker.IsBusy)
            worker.RunWorkerAsync();
    }

    void worker_DoWork(object sender, DoWorkEventArgs e)
    {
        BackgroundWorker w = (BackgroundWorker)sender;

        while(/*condition*/)
        {
            //check if cancellation was requested
            if(w.CancellationPending)
            {
                //take any necessary action upon cancelling (rollback, etc.)

                //notify the RunWorkerCompleted event handler
                //that the operation was cancelled
                e.Cancel = true; 
                return;
            }

            //report progress; this method has an overload which can also take
            //custom object (usually representing state) as an argument
            w.ReportProgress(/*percentage*/);

            //do whatever You want the background thread to do...
        }
    }

    void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        //display the progress using e.ProgressPercentage and/or e.UserState
    }

    void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        if(e.Cancelled)
        {
            //do something
        }
        else
        {
            //do something else
        }
    }
}

Then, in order to cancel further execution simply call worker.CancelAsync(). Note that this is completely user-handled cancellation mechanism (it does not support thread aborting or anything like that out-of-the-box).

Grx70
  • 10,041
  • 1
  • 40
  • 55
  • @Giorgi I used to use the `BackgroundWorker` a lot back when I was working with Forms (and Forms' timer) and never stumbled upon any problem. – Grx70 May 14 '15 at 05:18
  • 2
    @Giorgi I think your approach would work, but I've provided an example of how to accomplish it making full use of the `BackgroundWorker`. – Grx70 May 14 '15 at 07:30
  • @Giorgi: note that your `worker_DoWork()` method already has the `BackgroundWorker` instance. That's the object reference passed in the `sender` parameter. You can see that in the edited code example that was just added by the author. I don't think `CancellationToken` adds much over a plain `volatile bool` field, if you're just going to use it for its state. It's much more useful when dealing with cancellation of `Task` objects. – Peter Duniho May 15 '15 at 08:05
  • 1
    thats awesome but in the `elaborate example` I didn't understand the purpose of `while looop` – Basheer AL-MOMANI Jun 27 '16 at 10:33
  • 1
    @BasheerAL-MOMANI In order to report/cancel _"while"_ your work is in progress you need to split it into smaller batches and then repeat the *check for cancellation-report progress-process the batch* routine. Otherwise, you could report/cancel only before/after the **whole** work is done, which would be pointless. If you knew the number of batches at compile-time, you could of course _unroll_ the loop, but that's usually not the case. As for the `while` - it is just an example, you can just as well use `for`, `foreach` or any other kind of iteration. – Grx70 Jun 27 '16 at 11:01
23

You can just maintain a volatile bool to achieve what you asked:

private volatile bool _executing;

private void TimerElapsed(object state)
{
    if (_executing)
        return;

    _executing = true;

    try
    {
        // do the real work here
    }
    catch (Exception e)
    {
        // handle your error
    }
    finally
    {
        _executing = false;
    }
}
Matt Johnson-Pint
  • 230,703
  • 74
  • 448
  • 575
  • 2
    This is the answer based on the wording of OP's question. – Mike Marynowski Jan 26 '13 at 22:37
  • It is best to use lock or interlock. See this: http://stackoverflow.com/questions/154551/volatile-vs-interlocked-vs-lock – Umer Azaz Jan 31 '13 at 06:03
  • 3
    This is a reasonably safe use of `volatile` to prevent concurrency. It would be better practise to use `lock` or `Interlock`, but the long interval (minutes) makes it safe *enough*. – Paul Turner Jan 31 '13 at 10:12
  • @Giorgi: for what it's worth, the above _also_ would probably be an appropriate solution in your case. As noted [in another answer here](http://stackoverflow.com/a/14571702/3538012), there are many alternatives. The key is to pick one that works best for your needs. – Peter Duniho May 15 '15 at 08:08
  • @Giorgi - hard to say without seeing your code. Consider posting a new question. If I were to guess, I'd say that it might be challenging to set the flag back to false at the appropriate time. – Matt Johnson-Pint May 15 '15 at 12:17
  • @MattJohnson - Please explain why the `volatile` keyword is needed your code? Would it not work correctly without it? – stomy Jul 04 '19 at 00:29
  • @stomy - it's explained well in the docs: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/volatile – Matt Johnson-Pint Jul 04 '19 at 02:33
10

You can disable and enable your timer in its elapsed callback.

public void TimerElapsed(object sender, EventArgs e)
{
  _timer.Stop();

  //Do Work

  _timer.Start();
}
Appulus
  • 18,630
  • 11
  • 38
  • 46
scottm
  • 27,829
  • 22
  • 107
  • 159
  • 6
    Important to note that the timer will now fire every `(X minutes) + (however long this method takes to execute)`, instead of firing every X minutes and skipping the times when the event is still executing. – SomeWritesReserved Sep 24 '12 at 18:13
  • So just to be clear - this doesn't actually do what I want, correct? Instead of running it every X minutes unless it's already running, it actually runs it, waits X minutes, then runs it again. Correct? – Keith Palmer Jr. Sep 24 '12 at 20:20
8

You can just use the System.Threading.Timer and just set the Timeout to Infinite before you process your data/method, then when it completes restart the Timer ready for the next call.

    private System.Threading.Timer _timerThread;
    private int _period = 2000;

    public MainWindow()
    {
        InitializeComponent();

        _timerThread = new System.Threading.Timer((o) =>
         {
             // Stop the timer;
             _timerThread.Change(-1, -1);

             // Process your data
             ProcessData();

             // start timer again (BeginTime, Interval)
             _timerThread.Change(_period, _period);
         }, null, 0, _period);
    }

    private void ProcessData()
    {
        // do stuff;
    }
sa_ddam213
  • 42,848
  • 7
  • 101
  • 110
4

Using the PeriodicTaskFactory from my post here

CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();

Task task = PeriodicTaskFactory.Start(() =>
{
    Console.WriteLine(DateTime.Now);
    Thread.Sleep(5000);
}, intervalInMilliseconds: 1000, synchronous: true, cancelToken: cancellationTokenSource.Token);

Console.WriteLine("Press any key to stop iterations...");
Console.ReadKey(true);

cancellationTokenSource.Cancel();

Console.WriteLine("Waiting for the task to complete...");

Task.WaitAny(task);

The output below shows that even though the interval is set 1000 milliseconds, each iteration doesn't start until the work of the task action is complete. This is accomplished using the synchronous: true optional parameter.

Press any key to stop iterations...
9/6/2013 1:01:52 PM
9/6/2013 1:01:58 PM
9/6/2013 1:02:04 PM
9/6/2013 1:02:10 PM
9/6/2013 1:02:16 PM
Waiting for the task to complete...
Press any key to continue . . .

UPDATE

If you want the "skipped event" behavior with the PeriodicTaskFactory simply don't use the synchronous option and implement the Monitor.TryEnter like what Bob did here https://stackoverflow.com/a/18665948/222434

Task task = PeriodicTaskFactory.Start(() =>
{
    if (!Monitor.TryEnter(_locker)) { return; }  // Don't let  multiple threads in here at the same time.

    try
    {
        Console.WriteLine(DateTime.Now);
        Thread.Sleep(5000);
    }
    finally
    {
        Monitor.Exit(_locker);
    }

}, intervalInMilliseconds: 1000, synchronous: false, cancelToken: cancellationTokenSource.Token);

The nice thing about the PeriodicTaskFactory is that a Task is returned that can be used with all the TPL API, e.g. Task.Wait, continuations, etc.

Community
  • 1
  • 1
Jim
  • 4,910
  • 4
  • 32
  • 50
  • The goal isn't to start the countdown for the next task when the previous finished. The goal is to do something every X interval of time, but skipping any iterations fired while another is still running. Your timings *should* be every five to six seconds, not every six to seven, for it to meet the OP's requirements – Servy Sep 06 '13 at 17:11
  • 1
    I disagree. I read the OP comments and my solution would work for what he wants. His requirements: "I don't really care, as long as it doesn't run while the previous event is still running, and as long as they can't "stack" on top of each other (e.g. if the first session takes 15 minutes, it shouldn't then immediately run both of the missed sessions immediately after finishing the first)." – Jim Sep 06 '13 at 18:11
  • [This comment](http://stackoverflow.com/questions/12570324/c-sharp-run-a-thread-every-x-minutes-but-only-if-that-thread-is-not-running-alr/18662986?noredirect=1#comment16937935_12570333) to an answer with similar properties to yours makes it pretty clear it's not what's being asked for. Using a `lock` would also be wrong; it shouldn't "catch up" can run any skipped iterations; the top answer is a valid answer. It just ensures any iterations run while another is running do nothing. – Servy Sep 06 '13 at 18:18
  • Well his requirements from what I posted above actually come after the comment you are referencing so the comment you are referencing is an older requirement. As of Jan 30 he didn't care so long as the next iteration wouldn't run while the previous was running and they didn't "stack". This superseded the comment you referenced from Sept of last year. So unless the OP says so, my solution is an alternative that would work for him. – Jim Sep 06 '13 at 18:30
  • 1
    I have to agree with Jim. While this approach is a different way of solving the problem, it still solves the problem. Something runs every X milliseconds and it won't run until the previous task is done. Perhaps the OP won't prefer this approach, but it's worth seeing as a possibly good alternative to accomplish the problem. – Bob Horn Sep 06 '13 at 20:34
4

This question already has a number of good answers, including a slightly newer one that is based on some of the features in the TPL. But I feel a lack here:

  1. The TPL-based solution a) isn't really contained wholly here, but rather refers to another answer, b) doesn't show how one could use async/await to implement the timing mechanism in a single method, and c) the referenced implementation is fairly complicated, which somewhat obfuscates the underlying relevant point to this particular question.
  2. The original question here is somewhat vague on the specific parameters of the desired implementation (though some of that is clarified in comments). At the same time, other readers may have similar but not identical needs, and no one answer addresses the variety of design options that might be desired.
  3. I particularly like implementing periodic behavior using Task and async/await this way, because of the way it simplifies the code. The async/await feature in particular is so valuable in taking code that would otherwise be fractured by a continuation/callback implementation detail, and preserving its natural, linear logic in a single method. But no answer here demonstrates that simplicity.

So, with that rationale motivating me to add yet another answer to this question…


To me, the first thing to consider is "what exact behavior is desired here?" The question here starts with a basic premise: that the period task initiated by the timer should not run concurrently, even if the task takes longer than the timer period. But there are multiple ways that premise can be fulfilled, including:

  1. Don't even run the timer while the task is running.
  2. Run the timer (this and the remaining options I'm presenting here all assume the timer continues to run during the execution of the task), but if the task takes longer than the timer period, run the task again immediately after it's completed from the previous timer tick.
  3. Only ever initiate execution of the task on a timer tick. If the task takes longer than the timer period, don't start a new task while the current one is executed, and even once the current one has completed, don't start a new one until the next timer tick.
  4. If the task takes longer than the timer interval, not only run the task again immediately after it's completed, but run it as many times as necessary until the task has "caught up". I.e. over time, make a best effort to execute the task once for every timer tick.

Based on the comments, I have the impression that the #3 option most closely matches the OP's original request, though it sounds like the #1 option possibly would work too. But options #2 and #4 might be preferable to someone else.

In the following code example, I have implemented these options with five different methods (two of them implement option #3, but in slightly different ways). Of course, one would select the appropriate implementation for one's needs. You likely don't need all five in one program! :)

The key point is that in all of these implementations, they naturally and in a very simple way, execute the task in a period-but-non-concurrent way. That is, they effectively implement a timer-based execution model, while ensuring that the task is only ever being executed by one thread at a time, per the primary request of the question.

This example also illustrates how CancellationTokenSource can be used to interrupt the period task, taking advantage of await to handle the exception-based model in a clean, simple way.

class Program
{
    const int timerSeconds = 5, actionMinSeconds = 1, actionMaxSeconds = 7;

    static Random _rnd = new Random();

    static void Main(string[] args)
    {
        Console.WriteLine("Press any key to interrupt timer and exit...");
        Console.WriteLine();

        CancellationTokenSource cancelSource = new CancellationTokenSource();

        new Thread(() => CancelOnInput(cancelSource)).Start();

        Console.WriteLine(
            "Starting at {0:HH:mm:ss.f}, timer interval is {1} seconds",
            DateTime.Now, timerSeconds);
        Console.WriteLine();
        Console.WriteLine();

        // NOTE: the call to Wait() is for the purpose of this
        // specific demonstration in a console program. One does
        // not normally use a blocking wait like this for asynchronous
        // operations.

        // Specify the specific implementation to test by providing the method
        // name as the second argument.
        RunTimer(cancelSource.Token, M1).Wait();
    }

    static async Task RunTimer(
        CancellationToken cancelToken, Func<Action, TimeSpan, Task> timerMethod)
    {
        Console.WriteLine("Testing method {0}()", timerMethod.Method.Name);
        Console.WriteLine();

        try
        {
            await timerMethod(() =>
            {
                cancelToken.ThrowIfCancellationRequested();
                DummyAction();
            }, TimeSpan.FromSeconds(timerSeconds));
        }
        catch (OperationCanceledException)
        {
            Console.WriteLine();
            Console.WriteLine("Operation cancelled");
        }
    }

    static void CancelOnInput(CancellationTokenSource cancelSource)
    {
        Console.ReadKey();
        cancelSource.Cancel();
    }

    static void DummyAction()
    {
        int duration = _rnd.Next(actionMinSeconds, actionMaxSeconds + 1);

        Console.WriteLine("dummy action: {0} seconds", duration);
        Console.Write("    start: {0:HH:mm:ss.f}", DateTime.Now);
        Thread.Sleep(TimeSpan.FromSeconds(duration));
        Console.WriteLine(" - end: {0:HH:mm:ss.f}", DateTime.Now);
    }

    static async Task M1(Action taskAction, TimeSpan timer)
    {
        // Most basic: always wait specified duration between
        // each execution of taskAction
        while (true)
        {
            await Task.Delay(timer);
            await Task.Run(() => taskAction());
        }
    }

    static async Task M2(Action taskAction, TimeSpan timer)
    {
        // Simple: wait for specified interval, minus the duration of
        // the execution of taskAction. Run taskAction immediately if
        // the previous execution too longer than timer.

        TimeSpan remainingDelay = timer;

        while (true)
        {
            if (remainingDelay > TimeSpan.Zero)
            {
                await Task.Delay(remainingDelay);
            }

            Stopwatch sw = Stopwatch.StartNew();
            await Task.Run(() => taskAction());
            remainingDelay = timer - sw.Elapsed;
        }
    }

    static async Task M3a(Action taskAction, TimeSpan timer)
    {
        // More complicated: only start action on time intervals that
        // are multiples of the specified timer interval. If execution
        // of taskAction takes longer than the specified timer interval,
        // wait until next multiple.

        // NOTE: this implementation may drift over time relative to the
        // initial start time, as it considers only the time for the executed
        // action and there is a small amount of overhead in the loop. See
        // M3b() for an implementation that always executes on multiples of
        // the interval relative to the original start time.

        TimeSpan remainingDelay = timer;

        while (true)
        {
            await Task.Delay(remainingDelay);

            Stopwatch sw = Stopwatch.StartNew();
            await Task.Run(() => taskAction());

            long remainder = sw.Elapsed.Ticks % timer.Ticks;

            remainingDelay = TimeSpan.FromTicks(timer.Ticks - remainder);
        }
    }

    static async Task M3b(Action taskAction, TimeSpan timer)
    {
        // More complicated: only start action on time intervals that
        // are multiples of the specified timer interval. If execution
        // of taskAction takes longer than the specified timer interval,
        // wait until next multiple.

        // NOTE: this implementation computes the intervals based on the
        // original start time of the loop, and thus will not drift over
        // time (not counting any drift that exists in the computer's clock
        // itself).

        TimeSpan remainingDelay = timer;
        Stopwatch swTotal = Stopwatch.StartNew();

        while (true)
        {
            await Task.Delay(remainingDelay);
            await Task.Run(() => taskAction());

            long remainder = swTotal.Elapsed.Ticks % timer.Ticks;

            remainingDelay = TimeSpan.FromTicks(timer.Ticks - remainder);
        }
    }

    static async Task M4(Action taskAction, TimeSpan timer)
    {
        // More complicated: this implementation is very different from
        // the others, in that while each execution of the task action
        // is serialized, they are effectively queued. In all of the others,
        // if the task is executing when a timer tick would have happened,
        // the execution for that tick is simply ignored. But here, each time
        // the timer would have ticked, the task action will be executed.
        //
        // If the task action takes longer than the timer for an extended
        // period of time, it will repeatedly execute. If and when it
        // "catches up" (which it can do only if it then eventually
        // executes more quickly than the timer period for some number
        // of iterations), it reverts to the "execute on a fixed
        // interval" behavior.

        TimeSpan nextTick = timer;
        Stopwatch swTotal = Stopwatch.StartNew();

        while (true)
        {
            TimeSpan remainingDelay = nextTick - swTotal.Elapsed;

            if (remainingDelay > TimeSpan.Zero)
            {
                await Task.Delay(remainingDelay);
            }

            await Task.Run(() => taskAction());
            nextTick += timer;
        }
    }
}

One final note: I came across this Q&A after following it as a duplicate of another question. In that other question, unlike here, the OP had specifically noted they were using the System.Windows.Forms.Timer class. Of course, this class is used mainly because it has the nice feature that the Tick event is raised in the UI thread.

Now, both it and this question involve a task that is actually executed in a background thread, so the UI-thread-affinitied behavior of that timer class isn't really of particular use in those scenarios. The code here is implemented to match that "start a background task" paradigm, but it can easily be changed so that the taskAction delegate is simply invoked directly, rather than being run in a Task and awaited. The nice thing about using async/await, in addition to the structural advantage I noted above, is that it preserves the thread-affinitied behavior that is desirable from the System.Windows.Forms.Timer class.

Community
  • 1
  • 1
Peter Duniho
  • 68,759
  • 7
  • 102
  • 136
  • @Giorgi: it looks like you have been able to use at least one of the other answers here to address your original question. But I did want to call your attention to this approach, in case you find the `async`/`await` based implementation preferable for some reason. IMHO it's a good, modern replacement for the old, reliable `System.Windows.Forms.Timer`. :) – Peter Duniho May 15 '15 at 08:01
3

You can stop timer before the task and start it again after task completion this can make your take perform periodiacally on even interval of time.

public void myTimer_Elapsed(object sender, EventArgs e)
{
    myTimer.Stop();
    // Do something you want here.
    myTimer.Start();
}
Adil
  • 146,340
  • 25
  • 209
  • 204
3

If you want the timer's callback to fire on a background thread, you could use a System.Threading.Timer. This Timer class allows you to "Specify Timeout.Infinite to disable periodic signaling." as part of the constructor, which causes the timer to fire only a single time.

You can then construct a new timer when your first timer's callback fires and completes, preventing multiple timers from being scheduled until you are ready for them to occur.

The advantage here is you don't create timers, then cancel them repeatedly, as you're never scheduling more than your "next event" at a time.

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
3

There are at least 20 different ways to accomplish this, from using a timer and a semaphore, to volatile variables, to using the TPL, to using an opensource scheduling tool like Quartz etc al.

Creating a thread is an expensive exercise, so why not just create ONE and leave it running in the background, since it will spend the majority of its time IDLE, it causes no real drain on the system. Wake up periodically and do work, then go back to sleep for the time period. No matter how long the task takes, you will always wait at least the "waitForWork" timespan after completing before starting a new one.

    //wait 5 seconds for testing purposes
    static TimeSpan waitForWork = new TimeSpan(0, 0, 0, 5, 0);
    static ManualResetEventSlim shutdownEvent = new ManualResetEventSlim(false);
    static void Main(string[] args)
    {
        System.Threading.Thread thread = new Thread(DoWork);
        thread.Name = "My Worker Thread, Dude";
        thread.Start();

        Console.ReadLine();
        shutdownEvent.Set();
        thread.Join();
    }

    public static void DoWork()
    {
        do
        {
            //wait for work timeout or shudown event notification
            shutdownEvent.Wait(waitForWork);

            //if shutting down, exit the thread
            if(shutdownEvent.IsSet)
                return;

            //TODO: Do Work here


        } while (true);

    }
Keith
  • 1,119
  • 2
  • 12
  • 23
3

You can use System.Threading.Timer. Trick is to set the initial time only. Initial time is set again when previous interval is finished or when job is finished (this will happen when job is taking longer then the interval). Here is the sample code.

class Program
{


    static System.Threading.Timer timer;
    static bool workAvailable = false;
    static int timeInMs = 5000;
    static object o = new object(); 

    static void Main(string[] args)
    {
        timer = new Timer((o) =>
            {
                try
                {
                    if (workAvailable)
                    {
                        // do the work,   whatever is required.
                        // if another thread is started use Thread.Join to wait for the thread to finish
                    }
                }
                catch (Exception)
                {
                    // handle
                }
                finally
                {
                    // only set the initial time, do not set the recurring time
                    timer.Change(timeInMs, Timeout.Infinite);
                }
            });

        // only set the initial time, do not set the recurring time
        timer.Change(timeInMs, Timeout.Infinite);
    }
Umer Azaz
  • 459
  • 2
  • 8
  • 17
3

Why not use a timer with Monitor.TryEnter()? If OnTimerElapsed() is called again before the previous thread finishes, it will just be discarded and another attempt won't happen again until the timer fires again.

private static readonly object _locker = new object();

    private void OnTimerElapsed(object sender, ElapsedEventArgs e)
    {
        if (!Monitor.TryEnter(_locker)) { return; }  // Don't let  multiple threads in here at the same time.

        try
        {
            // do stuff
        }
        finally
        {
            Monitor.Exit(_locker);
        }
    }
Bob Horn
  • 33,387
  • 34
  • 113
  • 219
2

If I understand you correctly, you actually just want to ensure your thread is not running before you dispatch another thread. Let's say you have a thread defined in your class like so.

private System.Threading.Thread myThread;

You can do:

//inside some executed method
System.Threading.Timer t = new System.Threading.Timer(timerCallBackMethod, null, 0, 5000);

then add the callBack like so

private void timerCallBackMethod(object state)
{
     if(myThread.ThreadState == System.Threading.ThreadState.Stopped || myThread.ThreadState == System.Threading.ThreadState.Unstarted)
     {
        //dispatch new thread
     }
}
Chibueze Opata
  • 9,856
  • 7
  • 42
  • 65
  • Chubuez , I guess you are close to correct answer. But in you r example , you are checking if the thread has stopped and then exit it insted of starting a new thread – Mridul Raj Jan 25 '13 at 09:54
  • No, I'm refusing to start a new thread if the other one is still running :) – Chibueze Opata Jan 25 '13 at 10:08
  • myThread.ThreadState == System.Threading.ThreadState.Stopped holds true if mythread is stopped which is a contradiction to your comment – Mridul Raj Jan 25 '13 at 10:26
  • You missed the `return` statement. It means that if the statement holds true, further execution should be stopped. – Chibueze Opata Jan 29 '13 at 13:32
  • @MridulRaj 's onservation seems relevant. This answer should get more details (code, comments in code). – Stéphane Gourichon Jan 07 '16 at 14:07
  • Hmmm Mridul is correct. I guess it's one of those moments where pride makes you *refuse* to be wrong. Thanks @MridulRaj, StéphaneGourichon – Chibueze Opata Jan 07 '16 at 14:39
  • @ChibuezeOpata: I did not understand the 'return' comment, is there any issue with the code mentioned above. Does stopped state represent more than one situation like executed and stopped or anything else. I want to use this. Anything i need to be sure of? – Rajesh Mishra Aug 01 '16 at 09:08
  • @RajeshMishra the code above has been modified to work properly so no issues. – Chibueze Opata Aug 01 '16 at 12:11
2

I had the same problem some time ago and all I had done was using the lock{} statement. With this, even if the Timer wants to do anything, he is forced to wait, until the end of the lock-Block.

i.e.

lock
{    
     // this code will never be interrupted or started again until it has finished
} 

This is a great way to be sure, your process will work until the end without interrupting.

souichiro
  • 181
  • 1
  • 1
  • 8
1

This should do what you want. It executes a thread, then joins the thread until it has finished. Goes into a timer loop to make sure it is not executing a thread prematurely, then goes off again and executes.

using System.Threading;

public class MyThread
{
    public void ThreadFunc()
    {
        // do nothing apart from sleep a bit
        System.Console.WriteLine("In Timer Function!");
        Thread.Sleep(new TimeSpan(0, 0, 5));
    }
};

class Program
{
    static void Main(string[] args)
    {
        bool bExit = false;
        DateTime tmeLastExecuted;

        // while we don't have a condition to exit the thread loop
        while (!bExit)
        {
            // create a new instance of our thread class and ThreadStart paramter
            MyThread myThreadClass = new MyThread();
            Thread newThread = new Thread(new ThreadStart(myThreadClass.ThreadFunc));

            // just as well join the thread until it exits
            tmeLastExecuted = DateTime.Now; // update timing flag
            newThread.Start();
            newThread.Join();

            // when we are in the timing threshold to execute a new thread, we can exit
            // this loop
            System.Console.WriteLine("Sleeping for a bit!");

            // only allowed to execute a thread every 10 seconds minimum
            while (DateTime.Now - tmeLastExecuted < new TimeSpan(0, 0, 10));
            {
                Thread.Sleep(100); // sleep to make sure program has no tight loops
            }

            System.Console.WriteLine("Ok, going in for another thread creation!");
        }
    }
}

Should produce something like:

In Timer Function! Sleeping for a bit! Ok, going in for another thread creation! In Timer Function! Sleeping for a bit! Ok, going in for another thread creation! In Timer Function! ... ...

Hope this helps! SR

SolidRegardless
  • 427
  • 3
  • 17
1

The guts of this is the ExecuteTaskCallback method. This bit is charged with doing some work, but only if it is not already doing so. For this I have used a ManualResetEvent (canExecute) that is initially set to be signalled in the StartTaskCallbacks method.

Note the way I use canExecute.WaitOne(0). The zero means that WaitOne will return immediately with the state of the WaitHandle (MSDN). If the zero is omitted, you would end up with every call to ExecuteTaskCallback eventually running the task, which could be fairly disastrous.

The other important thing is to be able to end processing cleanly. I have chosen to prevent the Timer from executing any further methods in StopTaskCallbacks because it seems preferable to do so while other work may be ongoing. This ensures that both no new work will be undertaken, and that the subsequent call to canExecute.WaitOne(); will indeed cover the last task if there is one.

private static void ExecuteTaskCallback(object state)
{
    ManualResetEvent canExecute = (ManualResetEvent)state;

    if (canExecute.WaitOne(0))
    {
        canExecute.Reset();
        Console.WriteLine("Doing some work...");
        //Simulate doing work.
        Thread.Sleep(3000);
        Console.WriteLine("...work completed");
        canExecute.Set();
    }
    else
    {
        Console.WriteLine("Returning as method is already running");
    }
}

private static void StartTaskCallbacks()
{
    ManualResetEvent canExecute = new ManualResetEvent(true),
        stopRunning = new ManualResetEvent(false);
    int interval = 1000;

    //Periodic invocations. Begins immediately.
    Timer timer = new Timer(ExecuteTaskCallback, canExecute, 0, interval);

    //Simulate being stopped.
    Timer stopTimer = new Timer(StopTaskCallbacks, new object[]
    {
        canExecute, stopRunning, timer
    }, 10000, Timeout.Infinite);

    stopRunning.WaitOne();

    //Clean up.
    timer.Dispose();
    stopTimer.Dispose();
}

private static void StopTaskCallbacks(object state)
{
    object[] stateArray = (object[])state;
    ManualResetEvent canExecute = (ManualResetEvent)stateArray[0];
    ManualResetEvent stopRunning = (ManualResetEvent)stateArray[1];
    Timer timer = (Timer)stateArray[2];

    //Stop the periodic invocations.
    timer.Change(Timeout.Infinite, Timeout.Infinite);

    Console.WriteLine("Waiting for existing work to complete");
    canExecute.WaitOne();
    stopRunning.Set();
}
nick_w
  • 14,758
  • 3
  • 51
  • 71
1

I recommend to use Timer instead of thread, as it's lighter object. To achieve your goal you can do following.

using System.Timers;

namespace sample_code_1
{
    public class ClassName
    {
        Timer myTimer;
        static volatile bool isRunning;

        public OnboardingTaskService()
        {
             myTimer= new Timer();
             myTimer.Interval = 60000;
             myTimer.Elapsed += myTimer_Elapsed;
             myTimer.Start();
        }

        private void myTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            if (isRunning) return;
            isRunning = true;
            try
            {
                //Your Code....
            }
            catch (Exception ex)
            {
                //Handle Exception
            }
            finally { isRunning = false; }
        }
    }
}

Let me know if it helps.

CDspace
  • 2,639
  • 18
  • 30
  • 36