嗯...请原谅我提出这样模糊的问题,但我因为它而崩溃了,我找不到一个好的逻辑来实现它,或者至少是一个很好的图书馆为我做这样的事情。 / p>
我的应用程序应该以不同的时间间隔执行许多任务,其中一些任务只有在满足某些条件或其他方法完成后才需要执行等等。 [把它想象成一个方法依赖树] ...我想知道像巨大的在线游戏或这样的项目这样的大项目,他们如何组织他们的代码,以便在错误的时间内没有崩溃或执行某些方法或没有满足它的条件?
整个问题是在我的应用程序中我想要以下规格
答案 0 :(得分:7)
Reactive Extensions(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();
结果: