9

I have C# 2.0 codes that I am porting to C# 4.0. I want to make use of System.Task in place of the System.ThreadPool.QueueueUserWorkItem. I also want to make use of System.Task in place of System.Threading.Timer.

How do I create a periodic System.Task? I do not see anything on System.Task or System.TaskFactory.

Kind regards for consideration,

pKumara

Shimrod
  • 3,115
  • 2
  • 36
  • 56
  • What's wrong with a `Timer`? You can use the timer callback to start your new task if you want. – Todd Li Aug 02 '13 at 17:59
  • 1
    possible duplicate of [Is there a Task based replacement for System.Threading.Timer?](http://stackoverflow.com/questions/4890915/is-there-a-task-based-replacement-for-system-threading-timer) – Brian Gideon Aug 02 '13 at 18:07

2 Answers2

22

Use Observable.Interval or Observable.Timer. Timer allows you to pass in a dueTime

e.q.

           // Repeat every 2 seconds.
        IObservable<long> observable = Observable.Interval(TimeSpan.FromSeconds(2));

        // Token for cancelation
        CancellationTokenSource source = new CancellationTokenSource();

        // Create task to execute.
        Action action = (() => Console.WriteLine("Action started at: {0}", DateTime.Now));
        Action resumeAction = (() => Console.WriteLine("Second action started at {0}", DateTime.Now));

        // Subscribe the obserable to the task on execution.
        observable.Subscribe(x => { Task task = new Task(action); task.Start();
                                      task.ContinueWith(c => resumeAction());
        }, source.Token);

enter image description here

Martijn van Put
  • 3,293
  • 18
  • 17
3

You can try with Observable.Timer which Returns an observable sequence of timer.