2013-08-02 106 views
8

我有我正在移植到C#4.0的C#2.0代码。我想利用System.Task代替System.ThreadPool.QueueueUserWorkItem。我也想用System.Task代替System.Threading.Timer如何创建周期性任务

如何创建周期性System.Task?我没有看到System.TaskSystem.TaskFactory上的任何内容。

亲切的问候审议,

pKumara

+0

这有什么错了'Timer'?如果需要,您可以使用计时器回调开始新任务。 –

+1

可能的重复[是否有基于任务的替换System.Threading.Timer?](http://stackoverflow.com/questions/4890915/is-there-a-task-based-replacement-for-system-threading-定时器) –

回答

18

使用Observable.Interval或Observable.Timer。定时器允许你通过一个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

+0

非常感谢。我试图接受你的回答,但发生了未知的错误。 –

+0

奇怪,但很高兴它回答你的问题! –

+2

为了让Observable命名空间可用,您必须从NuGet包中添加'Reactive Extensions - Query library'。 – douglaslps