How to create periodic task

c#, multithreading

Solution

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);

Problem

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

Original source

Related problems