如何创建定期任务

Pra*_*bag 8 c# multithreading

我有C#2.0代码,我移植到C#4.0.我想用System.Task它代替System.ThreadPool.QueueueUserWorkItem.我也想用System.Task它代替System.Threading.Timer.

如何创建定期System.Task?我没有看到任何东西System.TaskSystem.TaskFactory.

亲切的考虑,

pKumara

Mar*_*Put 19

使用Observable.Interval或Observable.Timer.Timer允许您传入dueTime

EQ

           // 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);
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

  • 您必须从NuGet包中添加"Reactive Extensions - Query library"才能使Observable命名空间可用. (2认同)

小智 3

您可以尝试使用Observable.Timer它返回可观察的计时器序列。