反应式扩展(Rx.NET)可能会完成这项工作!http://msdn.microsoft.com/en-us/data/gg577609.aspx
例子:
此示例安排任务执行。
Console.WriteLine("Current time: {0}", DateTime.Now);
// Start event 30 seconds from now.
IObservable<long> observable = Observable.Timer(TimeSpan.FromSeconds(30));
// Token for cancelation
CancellationTokenSource source = new CancellationTokenSource();
// Create task to execute.
Task task = new Task(() => Console.WriteLine("Action started at: {0}", DateTime.Now));
// Subscribe the obserable to the task on execution.
observable.Subscribe(x => task.Start(), source.Token);
// If you want to cancel the task do:
//source.Cancel();
Console.WriteLine("Press any key to exit");
Console.ReadKey();
结果:
示例 2:
每 x 秒重复一次任务。
Console.WriteLine("Current time: {0}", DateTime.Now);
// 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));
// Subscribe the obserable to the task on execution.
observable.Subscribe(x => { Task task = new Task(action);task.Start(); },source.Token);
// If you want to cancel the task do:
//source.Cancel();
Console.WriteLine("Press any key to exit");
Console.ReadKey();
结果:
示例任务继续:
Console.WriteLine("Current time: {0}", DateTime.Now);
// 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);
// If you want to cancel the task do:
//source.Cancel();
Console.WriteLine("Press any key to exit");
Console.ReadKey();
结果: